blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 6
116
| path
stringlengths 5
872
| src_encoding
stringclasses 7
values | length_bytes
int64 10
4.68M
| score
float64 2.52
5.63
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 7
4.81M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
b5ff5f9979bbcb3eb4a92a0039bac88c62ed13fd
|
Swift
|
dungnc1607/UI
|
/UI/Extension/NSObject.swift
|
UTF-8
| 315
| 2.515625
| 3
|
[] |
no_license
|
//
// NSObject.swift
// UI
//
// Created by Squall on 7/12/18.
// Copyright © 2018 Squall. All rights reserved.
//
import Foundation
extension NSObject{
static var typeName:String{
return String(describing: self)
}
var objectName: String {
return String(describing: type(of: self))
}
}
| true
|
264514d7fb174f7f13d3b830a15bd43dd4619f9f
|
Swift
|
muyexi/Mogoroom-Demo
|
/Mogoroom Demo/ViewModel/CellViewModelProtocol.swift
|
UTF-8
| 242
| 2.625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
import UIKit
enum LoadingState: String {
case loading = "加载中..."
case success = "加载完成"
case failure = "加载失败"
}
protocol CellViewModelProtocol {
var api: APIProtocol { get }
func loadData()
}
| true
|
f898b3a1df4c9a096226bb56a6bd7cf767a3bf65
|
Swift
|
montioo/WWDC19_scholarship
|
/PID_Interactive_Montebaur.playground/Sources/RobotArmExample.swift
|
UTF-8
| 9,596
| 2.90625
| 3
|
[] |
no_license
|
//
// RobotArmExample.swift
// PID_Interactive_Montebaur
//
// Created by Marius Montebaur on 18.03.19.
// Copyright © 2019 Marius Montebaur. All rights reserved.
//
import SpriteKit
/* This example shows a robotic arm which the user can tune and control.
As the integral component of a PID controller is able to compensate a constant influence on the system, an example made to demonstrate this parameter's purpose should also offer some form of constant influence.
The robotic arm has a weight attatched to it which pulls the arm down. The force normally used to hold the arm in place is not enough to hold the arm's position. The parameter Ki can compensate this behaviour.
The user can also change the mass of the weight that the arm carries, to make sure the chosen parameter Ki does not only work for one weight.
*/
public class RobotArmExampleScene: SKScene {
private var sbKp : SliderNode!
private var sbKi : SliderNode!
private var sbKd : SliderNode!
private var lastKi : CGFloat = 0
private var joint1AngleSlider : SliderNode!
private var joint2AngleSlider : SliderNode!
private var weightSlider : SliderNode!
private var robotBase : SKSpriteNode!
private var weight : SKSpriteNode!
private var joint1PID : PIDController!
private var joint2PID : PIDController!
private var angleIndicator1 : SKSpriteNode!
private var angleIndicator2 : SKSpriteNode!
override public func didMove(to view: SKView) {
backgroundColor = NSColor.white
physicsWorld.gravity = CGVector(dx: 0, dy: -9.8)
physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 1, height: 1))
physicsBody?.isDynamic = false
joint1PID = PIDController()
joint1PID.maxChange = 0.2
joint2PID = PIDController()
joint2PID.maxChange = 0.2
sbKp = SliderNode(width: 150, title: "Change Kp")
sbKp.position = CGPoint(x: size.width * 0.25, y: size.height - 80)
sbKp.maxValue = 10; sbKp.minValue = 0; sbKp.currentValue = 5.21
sbKp.isHidden = true
addChild(sbKp)
sbKi = SliderNode(width: 150, title: "Change Ki")
sbKi.position = CGPoint(x: 363, y: 321 + 0.85 * 213)
sbKi.maxValue = 2; sbKi.minValue = 0; sbKi.currentValue = 0
addChild(sbKi)
sbKd = SliderNode(width: 150, title: "Change Kd")
sbKd.position = CGPoint(x: size.width * 0.75, y: size.height - 80)
sbKd.maxValue = 10; sbKd.minValue = 0; sbKd.currentValue = 1.56
sbKd.isHidden = true
addChild(sbKd)
joint1AngleSlider = SliderNode(width: 150, title: "Joint 1 Angle")
joint1AngleSlider.position = CGPoint(x: 363, y: 321 + 0.55 * 213)
joint1AngleSlider.setParams(min: 0, max: 1.3, current: 0.8)
addChild(joint1AngleSlider)
joint2AngleSlider = SliderNode(width: 150, title: "Joint 2 Angle")
joint2AngleSlider.position = CGPoint(x: 363, y: 321 + 0.35 * 213)
joint2AngleSlider.setParams(min: -1.3, max: 0.0, current: -0.5)
addChild(joint2AngleSlider)
weightSlider = SliderNode(width: 150, title: "Change Weight")
weightSlider.position = CGPoint(x: 363, y: 321 + 0.05 * 213)
weightSlider.setParams(min: 1, max: 2.5, current: 1)
addChild(weightSlider)
robotBase = SKSpriteNode(imageNamed: "RobotBase")
robotBase.position = CGPoint(x: 62 + robotBase.size.width/2, y: size.height - 223 - robotBase.size.height/2)
robotBase.physicsBody = SKPhysicsBody(rectangleOf: robotBase.size)
robotBase.physicsBody?.isDynamic = false
addChild(robotBase)
let armSec1 = SKSpriteNode(imageNamed: "Arm1")
armSec1.position = CGPoint(x: 6 + 40, y: 2.5 + 10)
armSec1.physicsBody = SKPhysicsBody(rectangleOf: armSec1.size)
armSec1.name = "armSec1"
armSec1.zPosition = -1
robotBase.addChild(armSec1)
let pin1Pos = armSec1.convert(CGPoint(x: -30, y: 0), to: scene!)
let joint1 = SKPhysicsJointPin.joint(withBodyA: robotBase.physicsBody!, bodyB: armSec1.physicsBody!, anchor: pin1Pos)
joint1.shouldEnableLimits = true
joint1.lowerAngleLimit = -0.1
joint1.upperAngleLimit = 1.4
joint1.frictionTorque = 0.1
scene?.physicsWorld.add(joint1)
angleIndicator1 = SKSpriteNode(color: .green, size: CGSize(width: 20, height: 3))
angleIndicator1.anchorPoint.x = 0
angleIndicator1.position = pin1Pos
angleIndicator1.zPosition = 20
addChild(angleIndicator1)
let armSec2 = SKSpriteNode(imageNamed: "Arm2")
armSec2.position = CGPoint(x: 20 + armSec2.size.width/2, y: 0)
armSec2.physicsBody = SKPhysicsBody(rectangleOf: armSec2.size)
armSec2.zPosition = 5
armSec2.name = "armSec2"
armSec1.addChild(armSec2)
let pin2Pos = armSec2.convert(CGPoint(x: -21.5, y: 0), to: scene!)
let joint2 = SKPhysicsJointPin.joint(withBodyA: armSec1.physicsBody!, bodyB: armSec2.physicsBody!, anchor: pin2Pos)
joint2.shouldEnableLimits = true
joint2.lowerAngleLimit = -1.4
joint2.upperAngleLimit = 0.1
joint2.frictionTorque = 0.1
scene?.physicsWorld.add(joint2)
angleIndicator2 = SKSpriteNode(color: .green, size: CGSize(width: 32, height: 3))
angleIndicator2.anchorPoint.x = 0
angleIndicator2.position = armSec2.convert(CGPoint(x: -21.5, y: 0), to: armSec1)
angleIndicator2.zPosition = 20
armSec1.addChild(angleIndicator2)
weight = SKSpriteNode(imageNamed: "Weight")
weight.anchorPoint.y = 1
weight.position = CGPoint(x: 25.5, y: 0)
weight.physicsBody = SKPhysicsBody(rectangleOf: weight.size, center: CGPoint(x: 0, y: -weight.size.height/2))
weight.name = "weight"
weight.zPosition = -1
armSec2.addChild(weight)
let pin3Pos = weight.convert(CGPoint(x: 0, y: 0), to: scene!)
let joint3 = SKPhysicsJointPin.joint(withBodyA: armSec2.physicsBody!, bodyB: weight.physicsBody!, anchor: pin3Pos)
joint3.frictionTorque = 0.005
scene?.physicsWorld.add(joint3)
let imageBorderPath = CGMutablePath()
imageBorderPath.addRects([CGRect(x: 0, y: 0, width: 213, height: 213)])
let imageBorder = SKShapeNode(path: imageBorderPath)
imageBorder.position = CGPoint(x: 39, y: size.height - 108 - imageBorder.frame.size.height)
imageBorder.fillColor = .clear
imageBorder.strokeColor = .black
addChild(imageBorder)
let imageTitle = PaperText(type: .ImageDescription, text: "Interactive Figure 2")
imageTitle.position = CGPoint(x: 39 + 213/2, y: size.height - 337)
addChild(imageTitle)
addChild(PaperText(type: .SectionTitle, text: "Interactive Example II: Robotic Arm"))
addChild(PaperText(type: .PageNumber, text: "Page 7"))
let descText = "The parameters of the controller for the left joint are already tuned. When changing the weight the arm has to lift, the torque used before to hold the arm's position is no longer the right value. Try to increase the weight and see the arm lower. Then adjust the parameter Ki to be around 1.4 and see the arm's movement compensate the weight. The green lines show the angle that each joint is supposed to hold."
let desc = PaperText(type: .TextSection, text: descText)
desc.position.y = size.height - 387
addChild(desc)
let navBtn = ButtonNode(imageNamed: "NextPageBtn", targetFunc: nextPage)
navBtn.position = CGPoint(x: 480 - 35 - navBtn.size.width/2, y: size.height - 557 - navBtn.size.height/2)
addChild(navBtn)
}
// Updates the UI with the currently desired rotations of each joint and also updates the PID controller's outputs.
override public func update(_ currentTime: TimeInterval) {
angleIndicator1.zRotation = joint1AngleSlider.currentValue
angleIndicator2.zRotation = joint2AngleSlider.currentValue
joint1PID.setParams(p: 5.39, i: 1.31, d: 7.5)
joint1PID.goal = joint1AngleSlider.currentValue
let thrust1 = joint1PID.calculate(measurement: robotBase["armSec1"][0].zRotation)
robotBase["armSec1"][0].physicsBody?.applyAngularImpulse(thrust1 * 0.02) // 0.01
if lastKi == 0 && sbKi.currentValue > 0 {
joint2PID.resetIntegral()
}
lastKi = sbKi.currentValue
joint2PID.setParams(p: sbKp.currentValue, i: sbKi.currentValue, d: sbKd.currentValue)
joint2PID.goal = joint2AngleSlider.currentValue
let thrust2 = joint2PID.calculate(measurement: robotBase["armSec1/armSec2"][0].zRotation)
robotBase["armSec1/armSec2"][0].physicsBody?.applyAngularImpulse(thrust2 * 0.005) // 0.005
let wSc = weightSlider.currentValue
weight.physicsBody!.density = wSc
let scale = 0.7 + (wSc / 8.33)
weight.setScale(scale)
}
// Transitions to the next page which is in this case the last of the interactive paper.
func nextPage() {
let endPage = EndPageScene(size: CGSize(width: 480, height: 640))
let transition = SKTransition.reveal(with: .left, duration: 0.7)
endPage.scaleMode = .aspectFill
scene?.view?.presentScene(endPage, transition: transition)
}
}
| true
|
60928ef29e678b9671f7ceb3a1ee9b450e570f19
|
Swift
|
koher/page-view-did-appear-experiment
|
/TabPageViewDidAppear/FooView.swift
|
UTF-8
| 1,070
| 2.796875
| 3
|
[] |
no_license
|
import SwiftUI
import UIKit
struct FooView: UIViewControllerRepresentable {
let page: Int
func makeUIViewController(context: Context) -> FooViewController {
let viewController = FooViewController()
viewController.page = page
return viewController
}
func updateUIViewController(_ uiViewController: FooViewController, context: Context) {
}
}
final class FooViewController: UIViewController {
var page: Int!
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Foo: \(page.description)"
view.addSubview(label)
NSLayoutConstraint.activate([
label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
label.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("viewDidAppear: \(page.description)")
}
}
| true
|
fda56311a4e29aa4ff2bbba1c19fb8b7f2ff7ef6
|
Swift
|
codevicky/WhiteBoardCodingChallenges
|
/WhiteBoardCodingChallengesTests/StaircaseTests.swift
|
UTF-8
| 663
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// StaircaseTests.swift
// WhiteBoardCodingChallenges
//
// Created by Boles on 07/05/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import XCTest
class StaircaseTests: XCTestCase {
// MARK: TestLifecycle
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
// MARK: Tests
func test_staircase() {
let staircase = Staircase.staircase(6)
print(staircase)
XCTAssertEqual(" #\n ##\n ###\n ####\n #####\n######", staircase, "Staircasing not valid")
}
}
| true
|
13882a191abd21936e41451095292f2b32eb9e55
|
Swift
|
feidora/Arsa-MC1
|
/Arsa MC1/Main Page/Profile and Edit Profile Page/ProfilePageVC.swift
|
UTF-8
| 2,295
| 2.625
| 3
|
[] |
no_license
|
//
// ProfilePageVC.swift
// Arsa MC1
//
// Created by Feidora Nadia Putri on 13/04/20.
// Copyright © 2020 Feidora Nadia Putri. All rights reserved.
//
import UIKit
class ProfilePageVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
var changedName = String()
var changedHeight = String()
var changedWeight = String()
var changedAge = String()
let menus = ["Dak Jun", "Spicy Kimchi Ramen", "Pumpkin Soup"]
// PP = Profile Page
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var nameLabelPP: UILabel!
@IBOutlet weak var heightWeightLabelPP: UILabel!
@IBOutlet weak var ageLabelPP: UILabel!
@IBOutlet weak var tableView: UITableView!
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "menuCell", for: indexPath)
cell.textLabel?.text = menus[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menus.count
}
override func viewDidLoad() {
super.viewDidLoad()
nameLabelPP.text = "Feidora"
heightWeightLabelPP.text = "150 cm / 43 kg"
ageLabelPP.text = "20"
// Do any additional setup after loading the view.
// nameLabelPP.text = changedName
// heightWeightLabelPP.text = "\(changedHeight) / \(changedWeight)"
// ageLabelPP.text = changedAge
tableView.delegate = self
tableView.dataSource = self
}
//
// func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// let favoriteMenu = menus[indexPath.row]
// performSegue(withIdentifier: "menuDetailsSegue", sender: favoriteMenu)
// }
//
// @IBAction func menuDetailsPressed(_ sender: Any) {
// performSegue(withIdentifier: "menuDetailsSegue", sender: self)
// }
@IBAction func unwindToProfile(_ sender: UIStoryboardSegue) {}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Hide the Navigation Bar
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
}
| true
|
cce619799b453273eabd8ad716e851062c671d6b
|
Swift
|
regexident/nio
|
/Nio/RootView.swift
|
UTF-8
| 1,146
| 2.53125
| 3
|
[
"MPL-2.0"
] |
permissive
|
import SwiftUI
struct RootView: View {
@EnvironmentObject var store: AccountStore
var body: some View {
switch store.loginState {
case .loggedIn(let userId):
return AnyView(
RecentRoomsContainerView()
.environment(\.userId, userId)
// Can this ever be nil? And if so, what happens with the default fallback?
.environment(\.homeserver, (store.client?.homeserver.flatMap(URL.init)) ?? HomeserverKey.defaultValue)
)
case .loggedOut:
return AnyView(
LoginContainerView()
)
case .authenticating:
return AnyView(
LoadingView()
)
case .failure(let error):
return AnyView(
VStack {
Text(error.localizedDescription)
Button(action: {
self.store.loginState = .loggedOut
}, label: {
Text(L10n.Login.failureBackToLogin)
})
}
)
}
}
}
| true
|
1abf0e8e4edfdc6f8d588aec8a9c4419b9532235
|
Swift
|
mohitkotie/Data-Structures-and-Algorithms-using-Swift
|
/Heap/Heap.swift
|
UTF-8
| 3,262
| 3.421875
| 3
|
[] |
no_license
|
class Heap {
var size : Int
var arr : [Int]
var isMin : Bool
public init(arrInput : [Int], isMin : Bool) {
self.size = arrInput.count
self.arr = [1]
self.arr.append(contentsOf : arrInput)
self.isMin = isMin
var i = (self.size / 2)
while i > 0 {
self.proclateDown(parent : i)
i-=1
}
}
public init(isMin : Bool) {
self.arr = [1]
self.size = 0
self.isMin = isMin
}
private func proclateDown(parent : Int) {
let lChild = 2 * parent
let rChild = lChild + 1
var small = -1
if lChild <= self.size {
small = lChild
}
if rChild <= self.size && self.comp(lChild, rChild) {
small = rChild
}
if small != -1 && self.comp(parent, small) {
self.arr.swapAt(parent, small)
self.proclateDown(parent : small)
}
}
private func comp(_ i : Int, _ j : Int) -> Bool { // always i < j in use
if self.isMin == true {
return self.arr[i] > self.arr[j] // swaps while min heap
}
return self.arr[i] < self.arr[j] // swap while max heap.
}
private func proclateUp(child : Int) {
let parent = child / 2
if parent == 0 {
return
}
if self.comp(parent, child) {
self.arr.swapAt(child, parent)
self.proclateUp(child : parent)
}
}
public func add(value : Int) {
self.size+=1
self.arr.append(value)
self.proclateUp(child : self.size)
}
public func remove() -> Int {
if self.isEmpty {
print("HeapEmptyException.")
return 0
}
let value = self.arr[1]
self.arr[1] = self.arr[self.size]
self.size-=1
self.proclateDown(parent : 1)
//self.arr = self.arr[0 : self.size+1]
return value
}
public func Print() {
print("Printing Heap size :\(self.size) :: ")
var i = 1
while i <= self.size {
print(self.arr[i],terminator:"")
i+=1
}
print()
}
public var isEmpty : Bool {
return self.size == 0
}
public func peek() -> Int {
if self.isEmpty {
print("Heap empty exception.")
return 0
}
return self.arr[1]
}
}
func IsMinHeap(_ arr : [Int]) -> Bool {
let size = arr.count
var i = 0
while i <= (size-2)/2 {
if 2*i+1 < size {
if arr[i] > arr[2*i+1] {
return false
}
}
if 2*i+2 < size {
if arr[i] > arr[2*i+2] {
return false
}
}
i+=1
}
return true
}
func IsMaxHeap(_ arr : [Int]) -> Bool {
let size = arr.count
var i = 0
while i <= (size-2)/2 {
if 2*i+1 < size {
if arr[i] < arr[2*i+1] {
return false
}
}
if 2*i+2 < size {
if arr[i] < arr[2*i+2] {
return false
}
}
i+=1
}
return true
}
func HeapSort(arrInput : inout [Int]) {
let hp = Heap(arrInput:arrInput, isMin:true)
let n = arrInput.count
var i = 0
while i < n {
arrInput[i] = hp.remove()
i+=1
}
}
// Testing code
var arr = [1, 9, 6, 7, 8, -1, 2, 4, 5, 3]
var hp = Heap(isMin : true)
let n = arr.count
var i = 0
while i < n {
hp.add(value : arr[i])
i+=1
}
i = 0
while i < n {
print(hp.remove(),terminator:" ")
i+=1
}
arr = [1, 9, 6, 7, 8, -1, 2, 4, 5, 3]
hp = Heap(arrInput : arr, isMin : true)
i = 0
while i < n {
print(hp.remove(),terminator:" ")
i+=1
}
print()
// Testing code
arr = [1, 9, 6, 7, 8, -1, 2, 4, 5, 3]
HeapSort(arrInput:&arr)
print(arr)
let bb = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(IsMinHeap(bb))
let cc = [9, 8, 7, 6, 5, 4, 3, 2, 1]
print(IsMaxHeap(cc))
print(IsMaxHeap(bb))
| true
|
d871d376163a5eb079552de5ec84380a64c4b61d
|
Swift
|
prostodemon007/Revolut
|
/Revolut/ExchangeManager.swift
|
UTF-8
| 3,140
| 2.71875
| 3
|
[] |
no_license
|
//
// ExchangeManager.swift
// Revolut
//
// Created by Oleg Ulitsionak on 03.07.16.
// Copyright © 2016 Alexei Rudakov. All rights reserved.
//
import UIKit
import AFNetworking
let kNotificationCurrencyRefreshed = "kNotificationCurrencyRefreshed"
private let serverUrl = "http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"
class ExchangeManager {
private static let availaibleCurrencies = ["USD","EUR","GBP"]
private static let currencySigns = ["$","€","£"]
private static var timer : NSTimer!
static var currencies : [Currency] = {
let currency = Currency()
currency.rate = 1
currency.shortName = "EUR"
currency.symbol = "€"
return [currency]
}()
static func refresh(completion : (succees : Bool) -> Void) {
let manager = AFHTTPSessionManager()
manager.responseSerializer = AFXMLParserResponseSerializer()
manager.POST(serverUrl, parameters: nil, progress: nil, success: { (task, object) in
let parser = object as! NSXMLParser
let dict = NSDictionary(XMLParser: parser)
let currenciesArr = dict["Cube"]!["Cube"]!!["Cube"] as! [[String:AnyObject]]
for currencyDict in currenciesArr {
let shortName = currencyDict["_currency"] as! String
let rate = (currencyDict["_rate"] as! String).floatValue
addOrUpdateCurrency(shortName, rate: rate)
}
if timer == nil {
timer = NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: #selector(refreshTimerTick), userInfo: nil, repeats: true)
}
completion(succees: true)
}) { (task, error) in
completion(succees: false)
}
}
@objc static func refreshTimerTick() {
refresh { (succees) in
NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: kNotificationCurrencyRefreshed, object: nil))
}
}
static func addOrUpdateCurrency(shortName : String, rate : Float) {
var found = false
for currency in currencies {
if shortName == currency.shortName {
currency.rate = rate
found = true
break
}
}
if !found {
for (index,shortN) in availaibleCurrencies.enumerate() {
if shortName == shortN {
let currency = Currency()
currency.rate = rate
currency.shortName = shortName
currency.symbol = currencySigns[index]
currencies.append(currency)
}
}
}
}
static func exchange(amount : Float, fromCurrency : Currency, toCurrency : Currency) -> Float {
return amount / fromCurrency.rate * toCurrency.rate
}
static func exchangeRevert(amount : Float, fromCurrency : Currency, toCurrency : Currency) -> Float {
return amount * fromCurrency.rate / toCurrency.rate
}
}
| true
|
c63470053344785b7935991ff130a2f7f0c6acdb
|
Swift
|
gudkeshkumar/MovieFinder
|
/MovieFinder/Modules/Details/Presenter/MovieDetailsPresenter.swift
|
UTF-8
| 934
| 2.859375
| 3
|
[] |
no_license
|
//
// MovieDetailsPresenter.swift
// MovieFinder
//
// Created by apple on 01/04/21.
//
import Foundation
final class MovieDetailsPresenter: MovieDetailsViewToPresenterProtocal {
weak var view: MovieDetailsPresenterToViewProtocol?
var interactor: MovieDetailsPresenterToInteractorProtocol?
var router: MovieDetailsPresenterToRouterProtocol?
var movie: MovieDetailsViewModel?
private var id: String?
init(with id: String?) {
self.id = id
}
func viewDidLoad() {
interactor?.fetchDetails(for: id)
}
}
extension MovieDetailsPresenter: MovieDetailsInteractorToPresenterProtocol {
func onDetailsFetchSuccess(data: MovieDetail) {
movie = MovieDetailsViewModel(data)
view?.onMovieDetailsFetchSuccess()
}
func onDetailsFetchFailure(error: String?) {
view?.onMovieDetailsFetchFailure(error: error)
}
}
| true
|
72cda660f91a2534017fe0c4e85968fbc42c68fe
|
Swift
|
mohsinalimat/firebase-chatapp
|
/Messaging/Common/Utils/BaseVC.swift
|
UTF-8
| 2,731
| 2.90625
| 3
|
[] |
no_license
|
/*
* BaseViewController is the base class for any
* ViewController in our application
* Right now it is not so useful, but maybe it is needed later
*/
import UIKit
import Toast
class BaseVC : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
prepareUI()
bindViewModel()
}
open func prepareUI() { }
open func bindViewModel() { }
open func handleError(e: Error) {
if let error = e as? SimpleError {
self.view.makeToast(error.message, duration: 3.0, position: CSToastPositionCenter)
} else if e is SessionExpireError {
self.logoutWithSessionExpire()
} else {
print("Unknown error: \(e)")
}
}
final func logoutWithSessionExpire() {
let alertController = UIAlertController(
title: "Session expired",
message: "The current session is expired, please login again. Sorry for this inconvenience.",
preferredStyle: .alert)
let defaultAction = UIAlertAction(
title: "Logout",
style: .cancel,
handler: { [unowned self] (_) in
self.doLogout()
})
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
final func logoutNormally() {
let alertController = UIAlertController(
title: "Logging out",
message: "You will not receive notification for incoming messages if you logout. Are you sure to proceed?",
preferredStyle: .alert)
let defaultAction = UIAlertAction(
title: "Logout",
style: .default,
handler: { [unowned self] (_) in
self.doLogout()
})
let cancelAction = UIAlertAction(title: "Cancel",
style: .cancel,
handler: nil)
alertController.addAction(defaultAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
@objc private func doLogout() {
let vc = LoginVC.instance()
let nc = UINavigationController(rootViewController: vc)
AppDelegate.sharedInstance.window?.rootViewController = nc
}
final func goToMainScreen() {
let vc = MainVC.instance()
AppDelegate.sharedInstance.window?.rootViewController = vc
}
final func doToast(with text: String, duration: Double = 3.0) {
self.view.makeToast(text, duration: duration, position: CSToastPositionBottom)
}
}
| true
|
d60263463f8b3665aff33f13d4ac7aef32290ae6
|
Swift
|
tienanht98/iosadv
|
/noteUsingCoreData/DBFactory.swift
|
UTF-8
| 461
| 2.75
| 3
|
[] |
no_license
|
//
// DBFactory.swift
// noteUsingCoreData
//
// Created by Trần Tiến Anh on 9/21/18.
// Copyright © 2018 iAnh. All rights reserved.
//
import Foundation
enum typeDB {
case SQL,CoreData
}
class DBFactory {
static func selectDB(type:typeDB) ->saveAbleProtocol //
{
switch type { // SQLite or Core Data
case .SQL:
return SQLiteMN()
case .CoreData:
return CoreDataMN()
}
}
}
| true
|
941b32e5fd83ced78112bfc15ecb5832d8ec456f
|
Swift
|
JonathanOh/DodgeIt
|
/DodgeIt/Views/ArrowPad/ArrowButton.swift
|
UTF-8
| 1,584
| 2.96875
| 3
|
[] |
no_license
|
//
// ArrowButton.swift
// DodgeIt
//
// Created by admin on 11/21/17.
// Copyright © 2017 esohjay. All rights reserved.
//
import UIKit
class ArrowButton: UIButton {
enum Direction {
case up
case right
case down
case left
}
init(target: Any?, action: Selector, direction: Direction) {
super.init(frame: .zero)
setupImage(direction: direction)
backgroundColor = .white//CONSTANTS.COLORS.MENU_BUTTONS
layer.borderColor = UIColor.black.cgColor
//layer.borderWidth = 2
layer.cornerRadius = 5
translatesAutoresizingMaskIntoConstraints = false
addTarget(target, action: action, for: .touchUpInside)
}
func setupImage(direction: Direction) {
let arrowImage = UIImage(imageLiteralResourceName: "arrow")
switch direction {
case .up:
setImage(arrowImage, for: .normal)
case .right:
setImage(UIImage(cgImage: arrowImage.cgImage!, scale: 1, orientation: UIImageOrientation.right), for: .normal)
case .down:
setImage(UIImage(cgImage: arrowImage.cgImage!, scale: 1, orientation: UIImageOrientation.down), for: .normal)
case .left:
setImage(UIImage(cgImage: arrowImage.cgImage!, scale: 1, orientation: UIImageOrientation.left), for: .normal)
}
//imageView?.image = UIImage(imageLiteralResourceName: "arrow")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
5cda8ec07b07625d2132ea15a974be76f909d4eb
|
Swift
|
WilderLopez/porter-ios
|
/QualityReaderQR/Utils/HelperClasses.swift
|
UTF-8
| 1,449
| 2.953125
| 3
|
[] |
no_license
|
//
// HelperClasses.swift
// QualityReaderQR
//
// Created by Wilder Lopez on 4/21/20.
// Copyright © 2020 Wilder Lopez. All rights reserved.
//
import Foundation
import SwiftUI
class TextBindingManager: ObservableObject {
@Published var text = "" {
didSet {
if text.count > characterLimit && oldValue.count <= characterLimit {
text = oldValue
}
}
}
init(limit: Int) {
characterLimit = limit
}
var characterLimit : Int
}
class Exporting {
static private func getDocutmensDirectory() -> URL{
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
print("All paths:\n \(path)")
return path[0]
}
static func toCSV(clients: [Client], filename: String) -> URL{
var csvText = "Nombre y Apellidos,CI,Veces Denegado\n"
for c in clients{
let newLine = "\(c.name),\(c.ci),\(c.denegateCount)\n"
csvText.append(newLine)
}
let url = self.getDocutmensDirectory().appendingPathComponent("\(filename).csv")
do{
try csvText.write(to: url, atomically: true, encoding: .utf8)
// let input = try String(contentsOf: url)
// print("The document wirted:\n \(input)")
}catch{
print(error.localizedDescription)
}
return url
}
}
| true
|
950cc3617f164a391bbc7f9de6d4cdbaa925906a
|
Swift
|
qiang512833564/Logo
|
/Logo/Main/View/DynamicTextLayer.swift
|
UTF-8
| 851
| 3.1875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// DynamicTextLayer.swift
// Logo
//
// Created by developer on 8/21/19.
// Copyright © 2019 iOSDevLog. All rights reserved.
//
import UIKit
class DynamicTextLayer : CATextLayer {
var adjustsFontSizeToFitWidth = false
override func layoutSublayers() {
super.layoutSublayers()
if adjustsFontSizeToFitWidth {
fitToFrame()
}
}
func fitToFrame(){
// Calculates the string size.
var stringSize: CGSize {
get { return (string as? String)!.size(ofFont: UIFont(name: (font as! UIFont).fontName, size: fontSize)!) }
}
// Adds inset from the borders. Optional
let inset: CGFloat = 2
// Decreases the font size until criteria met
while frame.width < stringSize.width + inset {
fontSize -= 1
}
}
}
| true
|
af6dcf3637d909687ac79373523da851e3a919fe
|
Swift
|
ushaliveGitHub/worldRegions
|
/worldRegions/CountryTableViewCell.swift
|
UTF-8
| 1,054
| 3.046875
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
//
// CountryTableViewCell.swift
// worldRegions
//
// Created by Usha Natarajan on 9/5/17.
// Copyright © 2017 Usha Natarajan. All rights reserved.
//
import UIKit
class CountryTableViewCell: UITableViewCell {
@IBOutlet weak var capitalLabel: UILabel!
@IBOutlet weak var demonymLabel: UILabel!
@IBOutlet weak var populationLabel: UILabel!
@IBOutlet weak var areakm2Label: UILabel!
@IBOutlet weak var regionLabel: UILabel!
@IBOutlet weak var continentLabel: UILabel!
var country:Country!{
didSet{
updateUI()
}
}
func updateUI(){
self.capitalLabel.text = country.capital
self.demonymLabel.text = country.demonym
self.populationLabel.text = String(country.population)
if country.area == 0 {
self.areakm2Label.text = "Unknown"
}else{
self.areakm2Label.text = String(country.area)
}
self.continentLabel.text = country.region
self.regionLabel.text = country.subregion
}
}//end of CountryTableViewCell
| true
|
e291d458336df05b9943c2845f93a0693161cd89
|
Swift
|
Djaflienda/eMstiF
|
/FitsMe/App/Scenes/Cards/View/CardView/ClothCard.swift
|
UTF-8
| 5,498
| 2.578125
| 3
|
[] |
no_license
|
//
// ClothCard.swift
// FitsMe
//
// Created by MacBook-Игорь on 03/03/2019.
// Copyright © 2019 Тигран Хачатурян. All rights reserved.
//
import UIKit
final class ClothCard: SwipableCard {
private var isExpanded: Bool = false
private var height: (expended: CGFloat, collapsed: CGFloat) = (150, 66)
private let descriptionView: UIView = {
let dv = UIView()
dv.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.9)
dv.layer.cornerRadius = 10
dv.clipsToBounds = true
return dv
}()
private let shadowContainer: UIView = {
let sc = UIView()
sc.layer.backgroundColor = UIColor.clear.cgColor
sc.layer.shadowColor = UIColor.black.cgColor
sc.layer.shadowRadius = 4.0
sc.layer.shadowOffset = CGSize(width: 0, height: -2)
sc.layer.shadowOpacity = 0.25
return sc
}()
private let storeLabel: UILabel = {
let sl = UILabel()
sl.font = UIFont.systemFont(ofSize: 16, weight: .bold)
return sl
}()
private let clothLabel: UILabel = {
let cl = UILabel()
cl.font = UIFont.systemFont(ofSize: 12, weight: .medium)
return cl
}()
private let infoButton: UIButton = {
let ib = UIButton()
ib.setImage(UIImage(named: "expandButton"), for: .normal)
ib.addTarget(self, action: #selector(infoButtonPressed), for: .touchUpInside)
return ib
}()
//MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.cornerRadius = 15
self.clipsToBounds = true
print("I was CREATED")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
convenience init(with data: Cloth) {
self.init(frame: .zero)
configureClothCard(with: data)
}
deinit {
print("I was DELETED")
}
func setupClothCard(target: UIViewController) {
target.view.addSubview(self)
self.anchor(centerX: target.view.centerXAnchor, top: target.view.safeAreaLayoutGuide.topAnchor, leading: target.view.leadingAnchor, trailing: target.view.trailingAnchor, bottom: target.view.bottomAnchor, padding: .init(top: 14, left: 14, bottom: 84, right: 14))
self.addSubview(shadowContainer)
shadowContainer.anchor(leading: self.leadingAnchor, trailing: self.trailingAnchor, bottom: self.bottomAnchor, padding: .init(top: 0, left: 7, bottom: 7, right: 7), size: .init(width: 0, height: 66))
shadowContainer.addSubview(descriptionView)
descriptionView.anchor(top: shadowContainer.topAnchor, leading: shadowContainer.leadingAnchor, trailing: shadowContainer.trailingAnchor, bottom: shadowContainer.bottomAnchor)
descriptionView.addSubviews(views: [infoButton, storeLabel, clothLabel])
infoButton.anchor(top: descriptionView.topAnchor, trailing: descriptionView.trailingAnchor, padding: .init(top: 21, left: 0, bottom: 0, right: 16), size: .init(width: 24, height: 24))
storeLabel.anchor(top: descriptionView.topAnchor, leading: descriptionView.leadingAnchor, trailing: infoButton.leadingAnchor, padding: .init(top: 14, left: 14, bottom: 0, right: 14), size: .init(width: 0, height: 14))
clothLabel.anchor(top: storeLabel.bottomAnchor, leading: descriptionView.leadingAnchor, trailing: descriptionView.trailingAnchor, padding: .init(top: 10, left: 14, bottom: 0, right: 14), size: .init(width: 0, height: 14))
target.view.sendSubviewToBack(self)
}
private func configureClothCard(with data: Cloth) {
isUserInteractionEnabled = true
contentMode = .scaleAspectFill
storeLabel.text = data.brand
clothLabel.text = "\(data.id)"
cacheImage(url: URL(string: data.pics[0].url)!)
}
func setGestureRecognizer() {
self.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handleCardPan)))
}
@objc private func infoButtonPressed() {
isExpanded.toggle()
UIView.animate(withDuration: 0.3, animations: {
if let constraint = (self.shadowContainer.constraints.filter{$0.firstAttribute == .height}.first) {
constraint.constant = self.isExpanded ? self.height.expended : self.height.collapsed
}
self.layoutIfNeeded()
self.infoButton.transform = CGAffineTransform(rotationAngle: self.isExpanded ? 3.1416 : 0)
})
}
}
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView {
func cacheImage(url: URL) {
image = nil
if let imageFromCache = imageCache.object(forKey: url as AnyObject) as? UIImage {
self.image = imageFromCache
return
}
URLSession.shared.dataTask(with: url) {
data, response, error in
print("UPLOAD PHOTO")
if let response = data {
DispatchQueue.main.async {
if let imageToCache = UIImage(data: response) {
imageCache.setObject(imageToCache, forKey: url as AnyObject)
self.image = imageToCache
} else {
print("no image found - CACHE FILE")
self.image = UIImage(named: "dummy_image")
}
}
}
}.resume()
}
}
| true
|
45214438dcf20bbce5e3d89ccdd31bb71d52f034
|
Swift
|
ginpei/ciccc-ios
|
/assignment03/WeatherApp/AppDelegate.swift
|
UTF-8
| 1,155
| 2.65625
| 3
|
[] |
no_license
|
//
// AppDelegate.swift
// WeatherApp
//
// Created by Derrick Park on 2017-05-26.
// Copyright © 2017 Derrick Park. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var cities = [City]()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// cities.append(City(name: "Vancouver"))
// cities.append(City(name: "Victoria"))
// cities.append(City(name: "Seattle"))
// cities.append(City(name: "San Francisco"))
// cities.append(City(name: "Los Angeles"))
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
let tab = UITabBarController()
window?.rootViewController = tab
tab.viewControllers = [
CityViewController(city: City(name: "Vancouver")),
CityViewController(city: City(name: "Victoria")),
]
window?.makeKeyAndVisible()
return true
}
}
| true
|
1d0a165040c3ce69f36447b4f6cdab56b121d363
|
Swift
|
nvv/MediaPocketIos
|
/MediaPocketIos/ContentView.swift
|
UTF-8
| 949
| 2.578125
| 3
|
[] |
no_license
|
//
// ContentView.swift
// MediaPocketIos
//
// Created by Vlad Namashko on 24.12.2020.
//
import SwiftUI
struct ContentView: View {
let podcasts: [Podcast] = load("data.json")
var body: some View {
let podcasts: [Podcast] = load("data.json")
let gridItemLayout = [GridItem(.flexible()), GridItem(.flexible())]
NavigationView {
ScrollView {
LazyVGrid(columns: gridItemLayout) {
ForEach(podcasts, id: \.self) { podcast in
NavigationLink(destination: PodcastDetailsView(podcast: podcast)) {
PodcastView(podcast: podcast)
}
}
}
}
.navigationBarHidden(true)
.padding(8)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
9b492f6671038f7362cceb7ad1f4a896c85f8757
|
Swift
|
stefanodem/ios-recipes
|
/Recipes/Recipes/View Controllers/RecipesTableViewController.swift
|
UTF-8
| 1,875
| 2.609375
| 3
|
[] |
no_license
|
//
// RecipesTableViewController.swift
// Recipes
//
// Created by De MicheliStefano on 06.08.18.
// Copyright © 2018 Lambda Inc. All rights reserved.
//
import UIKit
class RecipesTableViewController: UITableViewController, RecipeDetailViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Methods
func updateRecipes(recipe: Recipe, instructions: String) {
guard let networkClient = networkClient else { return }
networkClient.updateRecipes(for: recipe, instructions: instructions)
if let recipes = networkClient.loadFromPersistence() {
self.recipes = recipes
}
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeCell", for: indexPath)
cell.textLabel?.text = recipes[indexPath.row].name
return cell
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowRecipeDetail" {
guard let detailVC = segue.destination as? RecipeDetailViewController,
let indexPath = tableView.indexPathForSelectedRow else { return }
detailVC.recipe = recipes[indexPath.row]
detailVC.networkClient = networkClient
detailVC.delegate = self
}
}
// MARK: - Properties
var recipes: [Recipe] = [] {
didSet {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
var networkClient: RecipesNetworkClient?
}
| true
|
0cfa11868c6e25f8613c90c72cef6c12dad4983f
|
Swift
|
NinadPanchbhai/OCRPOCTalentServ
|
/OCRPOC/OCRPOC/ViewController.swift
|
UTF-8
| 1,900
| 2.703125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// OCRPOC
//
// Created by Talenserv Mac on 11/9/16.
// Copyright © 2016 Talenserv Mac. All rights reserved.
//
import UIKit
import TesseractOCR
class ViewController: UIViewController , G8TesseractDelegate {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var updateProgressPercentageLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
textView.text = recognizeTextFromImage(UIImage (named: "Lenore")!)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func activityIndicatorStartAnimating()
{
activityIndicator.startAnimating()
}
func activityIndicatorStopAnimating() {
activityIndicator.stopAnimating()
}
func recognizeTextFromImage(_ image : UIImage) -> String {
if let tesseract = G8Tesseract(language: "eng"){
tesseract.delegate = self
tesseract.image = image.g8_blackAndWhite()
tesseract.recognize()
return tesseract.recognizedText
}
else
{
return "error"
}
}
func progressImageRecognition(for tesseract: G8Tesseract!) {
print("Image Recognition Progress :: \(tesseract.progress) %")
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
ce7238fdf808853fedfc1ea02cf1b57a81f982c3
|
Swift
|
NingnNingYang/RxSwift-ImagePicker
|
/Education/UIView-Extension.swift
|
UTF-8
| 2,869
| 2.953125
| 3
|
[] |
no_license
|
//
// UIView-Extension.swift
// Education
//
// Created by 杨宁宁 on 2017/7/11.
// Copyright © 2017年 ynn. All rights reserved.
//
import UIKit
extension UIView {
var x : CGFloat {
get{
return self.frame.origin.x
}
set{
var frame = self.frame
frame.origin.x = self.x
self.frame = frame
}
}
var y : CGFloat {
get{
return self.frame.origin.y
}
set{
var frame = self.frame
frame.origin.y = self.y
self.frame = frame
}
}
var centerX : CGFloat {
get{
return self.center.x
}
set{
var center = self.center
center.x = self.centerX
self.center = center
}
}
var centerY : CGFloat {
get{
return self.center.y
}
set{
var center = self.center
center.y = self.centerY
self.center = center
}
}
var width : CGFloat {
get{
return self.frame.size.width
}
set{
var frame = self.frame
frame.size.width = width
self.frame = frame
}
}
var height : CGFloat {
get{
return self.frame.size.height
}
set{
var frame = self.frame
frame.size.height = height
self.frame = frame
}
}
var size : CGSize {
get{
return self.frame.size
}
set{
var frame = self.frame
frame.size = size
self.frame = frame
}
}
var origin : CGPoint {
get{
return self.frame.origin
}
set{
var frame = self.frame
frame.origin = origin
self.frame = frame
}
}
var left : CGFloat {
get{
return self.frame.origin.x
}
set{
var frame = self.frame
frame.origin.x = x
self.frame = frame
}
}
var top : CGFloat {
get{
return self.frame.origin.y
}
set{
var frame = self.frame
frame.origin.y = y
self.frame = frame
}
}
var right : CGFloat {
get{
return self.frame.origin.x + self.frame.size.width
}
set{
var frame = self.frame
frame.origin.x = right - frame.size.width
self.frame = frame
}
}
var bottom : CGFloat {
get{
return self.frame.origin.y + self.frame.size.height
}
set{
var frame = self.frame
frame.origin.y = bottom - frame.size.height
self.frame = frame
}
}
}
| true
|
aac9e23487ca920e46cb75a757ed00883805fa50
|
Swift
|
huxinguang/sleeptunes
|
/DeepSleep/SettingVC.swift
|
UTF-8
| 4,735
| 2.640625
| 3
|
[] |
no_license
|
//
// SettingVC.swift
// DeepSleep
//
// Created by xinguang hu on 2020/3/25.
// Copyright © 2020 wy. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class SettingVC: UITableViewController {
let titles = [["评分"],["意见反馈","关于","当前版本"]]
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return titles.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SettingContainerCell", for: indexPath) as! SettingContainerCell
cell.titles = titles[indexPath.section]
cell.tableView.rx.itemSelected.subscribe(onNext: { (subIndexPath) in
if indexPath.section == 0{
let appUrl = URL.init(string: "itms-apps://itunes.apple.com/app/id1507150138?action=write-review")!
if UIApplication.shared.canOpenURL(appUrl){
UIApplication.shared.open(appUrl, options: [:], completionHandler: nil)
}
}else{
switch subIndexPath.row {
case 0:
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc = storyboard.instantiateViewController(withIdentifier: "FeedbackVC")
self.navigationController?.pushViewController(vc, animated: true)
break
case 1:
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc = storyboard.instantiateViewController(withIdentifier: "AboutUsVC")
self.navigationController?.pushViewController(vc, animated: true)
break
default:
break
}
}
}).disposed(by: disposeBag)
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(titles[indexPath.section].count * 60 + 5*2)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 15
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.01
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
791bbb50978732de2895809d63e1baf4a8ef8f3b
|
Swift
|
DevWithLove/SaveALittle
|
/SaveALittle/Classes/Helpers/Color.swift
|
UTF-8
| 973
| 2.609375
| 3
|
[] |
no_license
|
//
// Color.swift
// SaveALittle
//
// Created by Tony Mu on 19/01/17.
// Copyright © 2017 DevWithLove.com. All rights reserved.
//
import Foundation
import UIKit
struct Color {
static let whiteColor = UIColor.white
static let orangeColor = UIColor(red: 247/255, green: 154/255, blue: 27/255, alpha: 1)
static let lightOrange = UIColor(r:235 ,g:147, b:123)
static let lightBlue = UIColor(red: 184/255, green: 197/255, blue: 214/255, alpha: 1)
// MARK: Background
static let darkBackground = UIColor(r:50 ,g:60, b:70)
static let darkBackgroundWith05alpha = UIColor(r: 50, g: 60, b: 70, a: 0.5)
static let darkerBackground = UIColor(r:38 ,g:47, b:56)
// MARK: Line
static let darkLine = UIColor(r:91 ,g:99, b:107)
// MARK: Text
static let darkerText = UIColor(r:60, g:79, b:94)
static let darkText = UIColor(r:98, g:116, b:133)
static let textColor = UIColor(white: 0.2, alpha: 1)
}
| true
|
c8c01cadf25945ef229037ad3b05482ed79ae0c2
|
Swift
|
dinghing/networkChecker
|
/networkChecker/CheckReachability.swift
|
UTF-8
| 3,921
| 2.828125
| 3
|
[] |
no_license
|
//
// CheckReachability.swift
// networkChecker
//
// Created by 丁琪 on 2/3/20.
// Copyright © 2020 丁琪. All rights reserved.
//
import Foundation
import SystemConfiguration
func CheckReachability(hostname:String)->Bool{
let reachability = SCNetworkReachabilityCreateWithName(nil, hostname)!
var flags = SCNetworkReachabilityFlags.connectionAutomatic
if !SCNetworkReachabilityGetFlags(reachability, &flags){
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
print(UInt32(kSCNetworkFlagsReachable))
return (isReachable && !needsConnection)
}
func CheckReachability(address:String)->Bool{
//ipv6
var addr6 = sockaddr_in6()
addr6.sin6_len = UInt8(MemoryLayout.size(ofValue: addr6))
addr6.sin6_family = sa_family_t(AF_INET6)
var ip = in6_addr()
_ = withUnsafeMutablePointer(to: &ip) {
inet_pton(AF_INET6, address, UnsafeMutablePointer($0))
}
addr6.sin6_addr = ip
//ipv4
var addr = sockaddr_in()
addr.sin_len = UInt8(MemoryLayout.size(ofValue: addr))
addr.sin_family = sa_family_t(AF_INET)
addr.sin_addr.s_addr = inet_addr(address)
var hostaddr = sockaddr_in()
hostaddr.sin_len = UInt8(MemoryLayout.size(ofValue: hostaddr))
hostaddr.sin_family = sa_family_t(AF_INET)
hostaddr.sin_addr.s_addr = inet_addr("8.8.8.8")
var hostaddr6 = sockaddr_in6()
hostaddr6.sin6_len = UInt8(MemoryLayout.size(ofValue: hostaddr6))
hostaddr6.sin6_family = sa_family_t(AF_INET6)
var ip6 = in6_addr()
_ = withUnsafeMutablePointer(to: &ip6) {
inet_pton(AF_INET6,"2001:4860:4860::8888", UnsafeMutablePointer($0))
}
hostaddr6.sin6_addr = ip6
let hostAddress = withUnsafePointer(to: &hostaddr6) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
return $0
}
}
print(hostAddress)
guard let reachability = withUnsafePointer(to: &addr6, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddressPair(kCFAllocatorDefault, $0, hostAddress)
}
})else{
return false
}
var flags = SCNetworkReachabilityFlags.connectionAutomatic
if !SCNetworkReachabilityGetFlags(reachability, &flags){
return false
}
let isReachable = flags.contains(.reachable)
print("isReachable is ",isReachable)
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags.connectionAutomatic
print("isConnectedToNetwork of flag is",flags.rawValue)
if SCNetworkReachabilityGetFlags(defaultRouteReachability , &flags) == false {
return false
}
let isReachable = flags == .reachable
let needsConnection = flags == .connectionRequired
let out = flags.subtracting(.reachable)
print("out is ",out)
print(isReachable)
return isReachable && !needsConnection
}
}
| true
|
11d4a58369134a6c00a61b4d48d0d08696343304
|
Swift
|
achinwo/JoliApi
|
/Sources/Lib/Http.swift
|
UTF-8
| 17,929
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
//
// File.swift
//
//
// Created by Anthony Chinwo on 30/10/2019.
//
import Foundation
extension Data {
public var stringUtf8: String? {
return String(data: self, encoding: .utf8)
}
}
public typealias MultilineString = String
public extension String {
func count(of needle: Character) -> Int {
return reduce(0) {
$1 == needle ? $0 + 1 : $0
}
}
}
@available(iOS, deprecated: 15.0, message: "Use the built-in API instead")
public extension URLSession {
func data(from url: URLRequest) async throws -> (Data, URLResponse) {
return try await withCheckedThrowingContinuation { continuation in
let task = self.dataTask(with: url) { data, response, error in
guard let data = data, let response = response else {
let error = error ?? URLError(.badServerResponse)
return continuation.resume(throwing: error)
}
continuation.resume(returning: (data, response))
}
task.resume()
}
}
}
public extension URL {
init(staticString: StaticString){
self.init(string: "\(staticString)")!
}
init(social: SocialLink){
self = social.url
}
static func fromString(_ string: String?) -> URL? {
guard let string = string else { return nil }
return Self.init(string: string)
}
}
public enum SocialLink: CustomStringConvertible {
case instagramUser(String)
case instagramHashtag(String)
case youtubeChannel(String)
case youtubeUser(String)
case twitterUser(String)
static func normalizeName(_ nameOrUrl: String) -> String {
return URL(string: nameOrUrl)?.lastPathComponent ?? nameOrUrl
}
public var normalizedName: String {
switch self {
case .instagramUser(let base), .instagramHashtag(let base), .youtubeChannel(let base), .youtubeUser(let base), .twitterUser(let base):
return Self.normalizeName(base)
}
}
public var description: String {
switch self {
case .instagramUser(let base):
return "@\(Self.normalizeName(base))"
case .instagramHashtag(let base):
return "#\(Self.normalizeName(base))"
case .youtubeChannel(let base), .youtubeUser(let base), .twitterUser(let base):
return Self.normalizeName(base)
}
}
public var url: URL {
switch self {
case .instagramUser(_), .twitterUser(_):
return baseUrl.appendingPathComponent(self.normalizedName, isDirectory: true)
case .instagramHashtag(_):
return baseUrl.appendingPathComponent("/explore/tags/\(self.normalizedName)", isDirectory: true)
case .youtubeChannel(_):
return baseUrl.appendingPathComponent("/channel/\(self.normalizedName)")
case .youtubeUser(_):
return baseUrl.appendingPathComponent("/user/\(self.normalizedName)")
}
}
public static var urls: (instagram: URL, youtube: URL, twitter: URL) {
return (
instagram: URL(staticString: "https://www.instagram.com"),
youtube: URL(staticString: "https://www.youtube.com"),
twitter: URL(staticString: "https://twitter.com")
)
}
public var baseUrl: URL {
switch self {
case .instagramUser(_), .instagramHashtag(_):
return Self.urls.instagram
case .youtubeChannel(_), .youtubeUser(_):
return Self.urls.youtube
case .twitterUser(_):
return Self.urls.twitter
}
}
}
public class HttpsHook: NSObject, URLSessionDelegate {
static let validIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
public let trustedHosts: [String]
public init(trustedHosts: [String]) {
self.trustedHosts = trustedHosts
}
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let allowConnect = {
//logger.debug("[HttpsHook] protectionSpace: \(challenge.protectionSpace) - \(challenge.protectionSpace.host)")
let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
//print("[HttpsHook] replacing: \(credential)")
challenge.sender?.use(credential, for: challenge)
completionHandler(URLSession.AuthChallengeDisposition.useCredential, credential)
}
let host = challenge.protectionSpace.host
guard host.range(of: HttpsHook.validIpAddressRegex, options: .regularExpression, range: nil, locale: nil) != nil else {
allowConnect()
return
}
let trustedHostArray: [String] = trustedHosts
//logger.debug("[HttpsHook] trusted: \(trustedHostArray) - \(challenge.protectionSpace.authenticationMethod)")
// if Utils.getEnviroment() == Constants.Environment.Production.rawValue {
// trustedHostArray = Constants.TRUSTED_HOSTS.Production
// } else {
// trustedHostArray = Constants.TRUSTED_HOSTS.Develop
// }
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
trustedHostArray.contains(challenge.protectionSpace.host) else {
return
}
allowConnect()
}
}
public extension Result {
var success: Success? {
switch self {
case .success(let success):
return success
default:
return nil
}
}
var error: Failure? {
switch self {
case .failure(let error):
return error
default:
return nil
}
}
}
public extension Result where Success == URLSessionWebSocketTask.Message {
var successTuple: (string: String?, data: Data?) {
switch self {
case .success(let success):
switch success {
case .string(let val):
return (string: val, data: nil)
case .data(let data):
return (string: nil, data: data)
@unknown default:
fatalError()
}
default:
return (string: nil, data: nil)
}
}
var successString: String? {
return successTuple.string
}
var successData: Data? {
return successTuple.data ?? successString?.data(using: .utf8)
}
var successJson: Json? {
guard let data = successData else { return nil }
return try? JSONSerialization.jsonObject(with: data, options: []) as? Json
}
var successResponse: WebSocketClient.Response? {
guard let data = successJson,
let topicUrl = data["topic"] as? String,
let url = URLComponents(string: topicUrl),
let body = data["data"] as? Json
else { return nil }
let subjectQ = url.queryItems?.first(where: { $0.name == "subject" })
return WebSocketClient.Response(topic: url.path, subject: subjectQ?.value, payload: body)
}
}
extension URLSession {
public func updated(configuration: URLSessionConfiguration, delegate: URLSessionDelegate? = nil, delegateQueue: OperationQueue? = nil) -> URLSession {
return URLSession.init(configuration: configuration,
delegate: delegate ?? self.delegate, delegateQueue: delegateQueue ?? self.delegateQueue)
}
}
public struct Auth: Codable, Hashable {
public var session: Session
public var user: User
}
public struct ErrorMessage: Codable, Error, Equatable {
public let status: Int
public let message: String?
public let type: String?
public let label: String?
}
public struct Response<T: Codable>: Codable {
public let data: T?
public let error: ErrorMessage?
}
public enum NetworkError: Error {
case invalidUrl(URLComponents, URL)
case badUrl(UrlConvertible, URL?)
case invalidUrlPath(String)
case badRequest(String)
case badResponse(String)
case errorMessage(ErrorMessage?)
case deserialization(String?, URLResponse?, Error)
}
public typealias Json = [String: AnyObject]
extension Json {
static func santized(_ json: Json) throws -> Json {
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "yyyy-MM-dd'T'hh:mm:ss"
let items: [Json.Element] = json.map() { item in
let value = item.value
switch value {
case let date as Date:
return (item.key, df.string(from: date) as AnyObject)
default:
return (item.key, item.value)
}
}
return Json(uniqueKeysWithValues: items)
}
public func toData(writingOptions: JSONSerialization.WritingOptions = []) throws -> Data {
return try JSONSerialization.data(withJSONObject: try Self.santized(self), options: writingOptions)
}
}
public enum HttpBody {
case data(Data)
case multipart(Json)
case json(Json)
case dbModel(DataConvertible)
case jsons([Json])
public func toData() throws -> Data {
switch self {
case .data(let data):
return data
case .multipart(let json):
return try json.toData()
case .json(let json):
return try json.toData()
case .dbModel(let model):
return try model.toData(outputFormatting: [])
case .jsons(let jsons):
var santized: [Json] = []
for json in jsons {
santized.append(try Json.santized(json))
}
return try JSONSerialization.data(withJSONObject: santized, options:.prettyPrinted)
}
}
}
public protocol UrlConvertible {
func url(relativeTo: URL?) -> URL?
}
extension String: UrlConvertible {
public func url(relativeTo: URL? = nil) -> URL? {
return URL(string: self, relativeTo: relativeTo)
}
}
extension URLComponents: UrlConvertible {
}
extension URL: UrlConvertible {
public func url(relativeTo: URL? = nil) -> URL? {
guard let rel = relativeTo else {
return self
}
return URLComponents(string: self.path)?.url(relativeTo: rel)
}
}
public enum HttpMethod: String {
public typealias Headers = [String: String]
public static var verbose = false
case get = "GET"
case post = "POST"
case delete = "DELETE"
case put = "PUT"
case head = "HEAD"
public enum Fetch {
public static func post<T: Codable>(url: UrlConvertible, dataType: T.Type, payload: HttpBody? = nil, baseUrl: URL? = nil, urlSession: URLSession? = nil) async throws -> T {
return try await HttpMethod.Fetch.execute(method: .post, url: url, dataType: dataType, payload: payload, baseUrl: baseUrl, urlSession: urlSession)
}
public static func delete<T: Codable>(url: UrlConvertible, dataType: T.Type, payload: HttpBody? = nil, baseUrl: URL? = nil, urlSession: URLSession? = nil) async throws -> T {
return try await HttpMethod.Fetch.execute(method: .delete, url: url, dataType: dataType, payload: payload, baseUrl: baseUrl, urlSession: urlSession)
}
public static func get<T: Codable>(url: UrlConvertible, dataType: T.Type, baseUrl: URL? = nil, urlSession: URLSession? = nil) async throws -> T {
return try await HttpMethod.Fetch.execute(method: .get, url: url, dataType: dataType, payload: nil, baseUrl: baseUrl, urlSession: urlSession)
}
public static func head<T: Codable>(url: UrlConvertible, dataType: T.Type, baseUrl: URL? = nil, urlSession: URLSession? = nil) async throws -> T {
return try await HttpMethod.Fetch.execute(method: .head, url: url, dataType: dataType, payload: nil, baseUrl: baseUrl, urlSession: urlSession)
}
public static func execute<T: Codable>(method: HttpMethod, url urlLike: UrlConvertible, dataType: T.Type, payload: HttpBody? = nil, baseUrl: URL? = nil, urlSession: URLSession? = nil) async throws -> T {
let baseUrl = baseUrl == nil ? (urlLike as? URL)?.baseURL ?? LocalhostApi.default.baseUrlHttp : baseUrl
guard let url = urlLike.url(relativeTo: baseUrl) else {
throw NetworkError.badUrl(urlLike, baseUrl)
}
return try await withCheckedThrowingContinuation { continuation in
let callback = { (data: Data?, resp: URLResponse?, error: Error?) -> Void in
guard let data = data else {
return continuation.resume(throwing: error ?? URLError(.badServerResponse))
}
do {
let respObj = try Session.jsonDecoder().decode(Response<T>.self, from: data)
guard let respData = respObj.data else {
let error = respObj.error != nil ?
NetworkError.errorMessage(respObj.error!) :
NetworkError.badResponse(data.stringUtf8 ?? "<<Data to string failed>>")
return continuation.resume(throwing: error)
}
continuation.resume(returning: respData)
} catch {
continuation.resume(throwing: NetworkError.deserialization(data.stringUtf8, resp, error))
}
}
let urlSession = urlSession ?? LocalhostApi.default.urlSession
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
let task: URLSessionTask
switch method {
case .post, .put:
guard let payloadData = try? (payload ?? .json([:])).toData() else {
return continuation.resume(throwing: NetworkError.badRequest("bad payload for post request: \(String(describing: payload))"))
}
task = urlSession.uploadTask(with: request, from: payloadData, completionHandler: callback)
case .get, .delete, .head:
task = urlSession.dataTask(with: request, completionHandler: callback)
}
task.resume()
}
}
}
public func fetchJson(urlPath: URLComponents, payload: Json, baseUrl: URL? = nil, urlSession: URLSession? = nil) async throws -> Json {
return try await fetchJson(urlPath: urlPath,
payload: .json(payload), baseUrl: baseUrl,
urlSession: urlSession)
}
public func fetchJson(urlPath: URLComponents, payload: HttpBody, baseUrl: URL? = nil, urlSession: URLSession? = nil) async throws -> Json {
let baseUrl = baseUrl ?? Track.baseUrl.http
guard let url = urlPath.url(relativeTo: baseUrl) else {
throw NetworkError.invalidUrl(urlPath, baseUrl)
}
return try await withCheckedThrowingContinuation { continuation in
let callback = { (data: Data?, resp: URLResponse?, error: Error?) -> Void in
guard let data = data else {
return continuation.resume(throwing: error ?? URLError(.badServerResponse))
}
do {
let respObj = try JSONSerialization.jsonObject(with: data, options: [])
continuation.resume(returning: respObj as! Json)
} catch {
continuation.resume(throwing: error)
}
}
guard let payloadData = try? payload.toData() else {
return continuation.resume(throwing: NetworkError.badRequest("bad paylod for post request: \(String(describing: payload))"))
}
let urlSession = urlSession ?? URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = self.rawValue
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
let task: URLSessionTask
switch self {
case .post, .put:
task = urlSession.uploadTask(with: request, from: payloadData, completionHandler: callback)
case .get, .delete, .head:
task = urlSession.dataTask(with: request, completionHandler: callback)
}
task.resume()
}
}
}
| true
|
6c6c6292da7d906004bcf9c99ea8d3818ddc8799
|
Swift
|
bradd123/ios-apps
|
/ios-nd-persistence-swift-3/CoolNotes/11-AutoSave/CoolNotes/NotesViewController.swift
|
UTF-8
| 1,179
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
//
// NotesViewController.swift
// CoolNotes
//
// Created by Fernando Rodríguez Romero on 11/03/16.
// Copyright © 2016 udacity.com. All rights reserved.
//
import UIKit
// MARK: - NotesViewController: CoreDataTableViewController
class NotesViewController: CoreDataTableViewController {
// MARK: TableView Data Source
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Get the note
let note = fetchedResultsController?.object(at: indexPath) as! Note
// Get the cell
let cell = tableView.dequeueReusableCell(withIdentifier: "Note", for: indexPath)
// Sync note -> cell
cell.textLabel?.text = note.text
// Return the cell
return cell
}
// MARK: Navigation
/*
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
c14f9e112d394247884dcf15ef6246ba7db2c60d
|
Swift
|
JasonTHChen/IOS-MemoryGame
|
/MemoryGame/ViewController.swift
|
UTF-8
| 8,999
| 2.671875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// MemoryGame
//
// Created by Jason Chen on 2018-04-14.
// Copyright © 2018 Jason Chen. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
@IBOutlet weak var gameView: UIView!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var turnLabel: UILabel!
@IBOutlet weak var resetButton: UIButton!
var tileWidth: CGFloat!
// to store both tiles and centers
var tilesArr: NSMutableArray = []
var centersArr: NSMutableArray = []
var curTime: Int = 0
var gameTimer: Timer?
var matched: Int = 0
var turns: Int = 0
var compareState: Bool = false
var firstTile: MyLabel!
var secondTile: MyLabel!
override func viewDidLoad()
{
super.viewDidLoad()
resetButton.layer.cornerRadius = 15
gameTimer = Timer()
}
override func viewDidAppear(_ animated: Bool) {
self.resetAction(Any.self)
}
func randomizeAction()
{
// go through the blocks in order and give them a random center
for tile in tilesArr
{
let randIndex: Int = Int(arc4random()) % centersArr.count
let randCenter: CGPoint = centersArr[randIndex] as! CGPoint
(tile as! MyLabel).center = randCenter
centersArr.removeObject(at: randIndex)
}
}
func blockMarkerAction()
{
tileWidth = gameView.frame.size.width / 4
var xCen: CGFloat = tileWidth / 2
var yCen: CGFloat = tileWidth / 2
let tileFrame:CGRect = CGRect(x: 0, y: 0, width: tileWidth - 4, height: tileWidth - 4)
var counter: Int = 1
for _ in 0..<4
{
for _ in 0..<4
{
let tile: MyLabel = MyLabel(frame: tileFrame)
if counter > 8
{
counter = 1
}
tile.text = String(counter)
tile.tagNumber = counter
tile.textAlignment = NSTextAlignment.center
tile.font = UIFont.boldSystemFont(ofSize: 20)
let cen: CGPoint = CGPoint(x: xCen, y: yCen)
tile.isUserInteractionEnabled = true
tile.center = cen
tile.backgroundColor = UIColor(red: 255/255, green: 153/255, blue: 159/255, alpha: 1.0) /* #ff999f */
gameView.addSubview(tile)
tilesArr.add(tile)
centersArr.add(cen)
xCen = xCen + tileWidth
counter += 1
}
yCen = yCen + tileWidth
xCen = tileWidth / 2
}
}
@IBAction func resetAction(_ sender: Any)
{
self.turns = 0
self.matched = 0
turnLabel.text = String(self.turns)
for anyView in gameView.subviews
{
anyView.removeFromSuperview()
}
tilesArr = []
centersArr = []
blockMarkerAction()
randomizeAction()
for anyTile in tilesArr
{
(anyTile as! MyLabel).text = "?"
(anyTile as! MyLabel).matched = false
(anyTile as! MyLabel).flipped = false
}
curTime = 0
gameTimer?.invalidate()
gameTimer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector: #selector(timerFunc),
userInfo: nil,
repeats: true)
}
@objc func timerFunc()
{
curTime += 1
let timeMins: Int = curTime / 60 // (110 / 60) = 1
let timeSecs: Int = curTime % 60 // (110 % 60) = 50
let timeStr: String = NSString(format: "%02d\' : %02d\"", timeMins, timeSecs) as String
timeLabel.text = timeStr
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let myTouch: UITouch = touches.first!
if (tilesArr.contains(myTouch.view as Any))
{
let thisTile: MyLabel = myTouch.view as! MyLabel
if !thisTile.matched && !thisTile.flipped
{
UIView.transition(with: thisTile,
duration: 0.75,
options: UIViewAnimationOptions.transitionFlipFromRight,
animations: {
thisTile.text = String(thisTile.tagNumber)
thisTile.backgroundColor = UIColor(displayP3Red: 183.0/255, green: 234.0/255, blue: 249.0/255, alpha: 1.0)
}, completion: {(true) in
if self.compareState
{
// let's compare
self.compareState = false
self.secondTile = thisTile
self.compareAction()
// comparison
}
else
{
// only flip
thisTile.flipped = true
self.firstTile = thisTile
self.compareState = true
}
})
}
}
}
func flipThemBack(anyInp: Array<Any>)
{
for anyObj in anyInp
{
let thisTile = anyObj as! MyLabel
thisTile.matched = true;
UIView.transition(with: thisTile,
duration: 0.75,
options: UIViewAnimationOptions.transitionFlipFromRight,
animations: {
thisTile.text = "👻"
thisTile.backgroundColor = UIColor(red: 83/255, green: 204/255, blue: 42/255, alpha: 1.0) /* #53cc2a */
}, completion: nil)
}
}
func compareAction()
{
self.turns += 1
turnLabel.text = String(self.turns)
print("We have items: \(firstTile.tagNumber) and \(secondTile.tagNumber)")
if firstTile.tagNumber == secondTile.tagNumber
{
matched += 1
if matched == 8
{
let timeMins: Int = curTime / 60 // (110 / 60) = 1
let timeSecs: Int = curTime % 60 // (110 % 60) = 50
let timeStr: String = NSString(format: "%02d\' : %02d\"", timeMins, timeSecs) as String
let alert = UIAlertController(title: "You Won",
message: "It took you \(timeStr) and \(self.turns) turns",
preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Play Again",
style: UIAlertActionStyle.default,
handler: {action in
switch action.style {
case .default:
self.resetAction(Any.self)
case .cancel: break
case .destructive: break
}
}))
self.present(alert, animated: true, completion: nil)
if gameTimer != nil
{
gameTimer?.invalidate()
gameTimer = nil
}
}
self.flipThemBack(anyInp: [firstTile, secondTile])
}
else
{
// they are different
firstTile.flipped = false
UIView.transition(with: self.view,
duration: 0.75,
options: UIViewAnimationOptions.transitionCrossDissolve,
animations: {
self.firstTile.text = "?"
self.secondTile.text = "?"
self.firstTile.backgroundColor = UIColor(red: 255/255, green: 153/255, blue: 159/255, alpha: 1.0) /* #ff999f */
self.secondTile.backgroundColor = UIColor(red: 255/255, green: 153/255, blue: 159/255, alpha: 1.0) /* #ff999f */
},
completion: nil)
}
}
}
class MyLabel: UILabel
{
var tagNumber: Int!
var matched: Bool = false
var flipped: Bool = false
}
| true
|
366d80e73c2d78c9fb224bddd4ac96994042623d
|
Swift
|
muruganandham/apollo-ios
|
/Tests/ApolloTests/MultipartFormDataTests.swift
|
UTF-8
| 7,301
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// MultipartFormDataTests.swift
// ApolloTests
//
// Created by Kim de Vos on 16/07/2019.
// Copyright © 2019 Apollo GraphQL. All rights reserved.
//
import XCTest
@testable import Apollo
class MultipartFormDataTests: XCTestCase {
func testSingleFile() throws {
let alphaFileUrl = Bundle(for: type(of: self)).url(forResource: "a", withExtension: "txt")!
let alphaData = try! Data(contentsOf: alphaFileUrl)
let formData = MultipartFormData(boundary: "------------------------cec8e8123c05ba25")
try formData.appendPart(string: "{ \"query\": \"mutation ($file: Upload!) { singleUpload(file: $file) { id } }\", \"variables\": { \"file\": null } }", name: "operations")
try formData.appendPart(string: "{ \"0\": [\"variables.file\"] }", name: "map")
formData.appendPart(data: alphaData, name: "0", contentType: "text/plain", filename: "a.txt")
let expectation = """
--------------------------cec8e8123c05ba25
Content-Disposition: form-data; name="operations"
{ "query": "mutation ($file: Upload!) { singleUpload(file: $file) { id } }", "variables": { "file": null } }
--------------------------cec8e8123c05ba25
Content-Disposition: form-data; name="map"
{ "0": ["variables.file"] }
--------------------------cec8e8123c05ba25
Content-Disposition: form-data; name="0"; filename="a.txt"
Content-Type: text/plain
Alpha file content.
--------------------------cec8e8123c05ba25--
"""
// Replacing CRLF with new line as string literals uses new lines
XCTAssertEqual(String(data: try formData.encode(), encoding: .utf8)!.replacingOccurrences(of: MultipartFormData.CRLF, with: "\n"), expectation)
}
func testMultifileFile() throws {
let bravoFileUrl = Bundle(for: type(of: self)).url(forResource: "b", withExtension: "txt")!
let charlieFileUrl = Bundle(for: type(of: self)).url(forResource: "c", withExtension: "txt")!
let bravoData = try! Data(contentsOf: bravoFileUrl)
let charlieData = try! Data(contentsOf: charlieFileUrl)
let formData = MultipartFormData(boundary: "------------------------ec62457de6331cad")
try formData.appendPart(string: "{ \"query\": \"mutation($files: [Upload!]!) { multipleUpload(files: $files) { id } }\", \"variables\": { \"files\": [null, null] } }", name: "operations")
try formData.appendPart(string: "{ \"0\": [\"variables.files.0\"], \"1\": [\"variables.files.1\"] }", name: "map")
formData.appendPart(data: bravoData, name: "0", contentType: "text/plain", filename: "b.txt")
formData.appendPart(data: charlieData, name: "1", contentType: "text/plain", filename: "c.txt")
let expectation = """
--------------------------ec62457de6331cad
Content-Disposition: form-data; name="operations"
{ "query": "mutation($files: [Upload!]!) { multipleUpload(files: $files) { id } }", "variables": { "files": [null, null] } }
--------------------------ec62457de6331cad
Content-Disposition: form-data; name="map"
{ "0": ["variables.files.0"], "1": ["variables.files.1"] }
--------------------------ec62457de6331cad
Content-Disposition: form-data; name="0"; filename="b.txt"
Content-Type: text/plain
Bravo file content.
--------------------------ec62457de6331cad
Content-Disposition: form-data; name="1"; filename="c.txt"
Content-Type: text/plain
Charlie file content.
--------------------------ec62457de6331cad--
"""
// Replacing CRLF with new line as string literals uses new lines
XCTAssertEqual(String(data: try formData.encode(), encoding: .utf8)!.replacingOccurrences(of: MultipartFormData.CRLF, with: "\n"), expectation)
}
func testBatchFile() throws {
let alphaFileUrl = Bundle(for: type(of: self)).url(forResource: "a", withExtension: "txt")!
let bravoFileUrl = Bundle(for: type(of: self)).url(forResource: "b", withExtension: "txt")!
let charlieFileUrl = Bundle(for: type(of: self)).url(forResource: "c", withExtension: "txt")!
let alphaData = try! Data(contentsOf: alphaFileUrl)
let bravoData = try! Data(contentsOf: bravoFileUrl)
let charlieData = try! Data(contentsOf: charlieFileUrl)
let formData = MultipartFormData(boundary: "------------------------627436eaefdbc285")
try formData.appendPart(string: "[{ \"query\": \"mutation ($file: Upload!) { singleUpload(file: $file) { id } }\", \"variables\": { \"file\": null } }, { \"query\": \"mutation($files: [Upload!]!) { multipleUpload(files: $files) { id } }\", \"variables\": { \"files\": [null, null] } }]", name: "operations")
try formData.appendPart(string: "{ \"0\": [\"0.variables.file\"], \"1\": [\"1.variables.files.0\"], \"2\": [\"1.variables.files.1\"] }", name: "map")
formData.appendPart(data: alphaData, name: "0", contentType: "text/plain", filename: "a.txt")
formData.appendPart(data: bravoData, name: "1", contentType: "text/plain", filename: "b.txt")
formData.appendPart(data: charlieData, name: "2", contentType: "text/plain", filename: "c.txt")
let expectation = """
--------------------------627436eaefdbc285
Content-Disposition: form-data; name="operations"
[{ "query": "mutation ($file: Upload!) { singleUpload(file: $file) { id } }", "variables": { "file": null } }, { "query": "mutation($files: [Upload!]!) { multipleUpload(files: $files) { id } }", "variables": { "files": [null, null] } }]
--------------------------627436eaefdbc285
Content-Disposition: form-data; name="map"
{ "0": ["0.variables.file"], "1": ["1.variables.files.0"], "2": ["1.variables.files.1"] }
--------------------------627436eaefdbc285
Content-Disposition: form-data; name="0"; filename="a.txt"
Content-Type: text/plain
Alpha file content.
--------------------------627436eaefdbc285
Content-Disposition: form-data; name="1"; filename="b.txt"
Content-Type: text/plain
Bravo file content.
--------------------------627436eaefdbc285
Content-Disposition: form-data; name="2"; filename="c.txt"
Content-Type: text/plain
Charlie file content.
--------------------------627436eaefdbc285--
"""
// Replacing CRLF with new line as string literals uses new lines
XCTAssertEqual(String(data: try formData.encode(), encoding: .utf8)!.replacingOccurrences(of: MultipartFormData.CRLF, with: "\n"), expectation)
}
}
| true
|
79c592eeedb0fc20a69acc09cc41eb9ae416c0cc
|
Swift
|
jieunpark247/Petsitter
|
/FoodTracker/Controller/ParentLoginViewController.swift
|
UTF-8
| 3,879
| 2.609375
| 3
|
[] |
no_license
|
//
// ParentLoginViewController.swift
// FoodTracker
//
// Created by SWUCOMPUTER on 2017. 11. 17..
// Copyright © 2017년 Apple Inc. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import GoogleSignIn
import FirebaseMessaging
class ParentLoginViewController: UIViewController, UITextFieldDelegate,GIDSignInUIDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
//displayLabel.text = textField.text
return true
}
@IBOutlet var idTextField: UITextField!
@IBOutlet var pwTextField: UITextField!
@IBOutlet var signInButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
// if Auth.auth().currentUser != nil{
// self.presentLoggedInScreen()
// }
GIDSignIn.sharedInstance().uiDelegate = self //델리게이트
//키값이 맞으면 자동로그인
if UserDefaults.standard.bool(forKey: "USERLOGGEDIN") == true{
//user is already logged in just navigate him to home screen
self.presentLoggedInScreen()
}
}
@IBAction func loginTapped(_ sender: UIButton) {
if let email = idTextField.text, let password = pwTextField.text{
Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
if let firebaseError = error{
print(firebaseError.localizedDescription)
return
}
//각자 아이디별로 토큰이 만들어어진다.
let uid = Auth.auth().currentUser?.uid
let token = InstanceID.instanceID().token()
// let fcmToken=Messaging.messaging().fcmToken
Database.database().reference().child("Parent Users").child(uid!).updateChildValues(["pushToken":token!]) // 내 데이터베이스 계정에 넣어준다. setvalue 는 기존 데이터 다 날라감 update를 해서 덮어씌워줘야 한다.
// print("Firebase registration token: \(fcmToken)")
print("FCM token: \(token ?? "")")
print("success!")
//자동 로그인하기위해 아이디비번이 맞다면 키값 저장
UserDefaults.standard.set(true, forKey: "USERLOGGEDIN")
self.presentLoggedInScreen()
})
}
}
func presentLoggedInScreen(){
let storyboard:UIStoryboard = UIStoryboard(name:"Main", bundle: nil)
let loggedInVC:ParentViewController = storyboard.instantiateViewController(withIdentifier: "ParentViewController") as! ParentViewController
//self.present(loggedInVC, animated: true, completion: nil)
self.navigationController!.pushViewController(loggedInVC, animated: true)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
idTextField.resignFirstResponder()
pwTextField.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func SignInButton(_ sender: Any) {
GIDSignIn.sharedInstance().signIn() //회원가입 신청
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
1d149da1f32da56bf7f6b5ec04b08f35cee08b43
|
Swift
|
Sia-z/Match-App
|
/MatchGamePractice/CardModel.swift
|
UTF-8
| 1,923
| 3.5625
| 4
|
[] |
no_license
|
//
// CardModel.swift
// MatchGamePractice
//
// Created by Siyao on 2020/2/26.
// Copyright © 2020 Siyao. All rights reserved.
//
import Foundation
class CardModel {
func getCards() -> [Card] {
// Declare an array to store numbers are already generated
var generateNumbers = [Int]()
// Declare an array to store the generated cards
var generatedCardsArray = [Card]()
// Randomly generate pairs of cards
while generateNumbers.count < 8 { // To have 8 pairs
let randomeNumber = arc4random_uniform(13) + 1
if generateNumbers.contains(Int(randomeNumber)) == false{
// Store the number into the generatNumber
generateNumbers.append(Int(randomeNumber))
// Create the first card
let cardOne = Card()
cardOne.imageName = "card\(randomeNumber)"
generatedCardsArray.append(cardOne)
// Create the second card
let cardTwo = Card()
cardTwo.imageName = "card\(randomeNumber)"
generatedCardsArray.append(cardTwo)
}
}
// TODO: Randomize the array
for i in 0...generatedCardsArray.count-1 {
// Find a random index to swap with
let randomNumber = Int(arc4random_uniform(UInt32(generatedCardsArray.count)))
let temporaryStorage = generatedCardsArray[i]
generatedCardsArray[i] = generatedCardsArray[randomNumber]
generatedCardsArray[randomNumber] = temporaryStorage
}
// Return the array
return generatedCardsArray
}
}
| true
|
d428800dce3695f1d97d0237bc016d49b7cece7a
|
Swift
|
tuynumemories/TwitSplit_iOS
|
/TwitSplit_iOS/TwitSplit_iOS/TwitSplitVC.swift
|
UTF-8
| 1,423
| 2.625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// TwitSplit_iOS
//
// Created by dat on 9/15/17.
// Copyright © 2017 dat. All rights reserved.
//
import UIKit
class TwitSplitVC: UIViewController {
@IBOutlet weak var tfUserMessage: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnPostMessageClicked(_ sender: UIButton) {
// show posting notification to UI
self.view.makeToastActivity("Posting message...", .center)
// processing message should use in background thread to protect UI
DispatchQueue.global().async {
[weak self] in
// processing input message
let sendMessage = UtilFunctions.splitMessage(self?.tfUserMessage.text)
// back to main thread to show result to UI
DispatchQueue.main.sync {
self?.view.hideToastActivity()
var messageResult = "Success!"
if sendMessage == nil {
messageResult = "Error!"
}
self?.view.makeToast(messageResult, duration: 2.0, position: .center)
}
}
}
}
| true
|
67018a8056feacc1b9f56a16da3df94b2ed5a3e5
|
Swift
|
takometonidze01/Shopywood
|
/Shopywood/Infrastructure/Managers/CategoryManager.swift
|
UTF-8
| 769
| 2.765625
| 3
|
[] |
no_license
|
//
// CategoryManager.swift
// Shopywood
//
// Created by CodergirlTM on 19.07.21.
//
import Foundation
protocol CategoryManagerProtocol: AnyObject {
func fetchCategory(completion: @escaping ((Result<[Category], Error>) -> Void))
}
class CategoryManager: CategoryManagerProtocol {
func fetchCategory(completion: @escaping ((Result<[Category], Error>) -> Void)) {
let url = "https://run.mocky.io/v3/8d8751ce-bed5-4b10-9566-ee269c869f6c"
NetworkManager.shared.get(url: url) { (result: Result<[Category], Error>) in
switch result {
case .success(let response):
completion(.success(response))
case .failure(let err):
completion(.failure(err))
}
}
}
}
| true
|
6f3ae6f2a32fa4b2308bc34358ef61f72e401675
|
Swift
|
didik-maulana/pixa-game-apps
|
/PixaGame/Network/NetworkService.swift
|
UTF-8
| 3,064
| 2.875
| 3
|
[] |
no_license
|
//
// NetworkService.swift
// PixaGame
//
// Created by Didik on 07/07/20.
// Copyright © 2020 Codingtive. All rights reserved.
//
import Foundation
enum NetworkError: Error {
case apiError
case invalidEndpoint
case invalidResponse
case emptyData
case serializationError
var localizedDescription: String {
switch self {
case .apiError:
return "Failed to fetch data"
case .invalidEndpoint:
return "Invalid endpoint"
case .invalidResponse:
return "Invalid response"
case .emptyData:
return "Empty data"
case .serializationError:
return "Failed to decode data"
}
}
}
class NetworkService {
static let shared = NetworkService()
private let urlSession = URLSession.shared
private let jsonDecoder = Utils.jsonDecoder
func loadURLAndDecode<D: Decodable>(
url: URL,
params: [String: String]? = nil,
completion: @escaping (Result<D, NetworkError>) -> ()
) {
guard var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
completion(.failure(.invalidEndpoint))
return
}
var queryItems: [URLQueryItem] = []
if let params = params {
queryItems.append(contentsOf: params.map {
URLQueryItem(name: $0.key, value: $0.value)
})
urlComponents.queryItems = queryItems
}
guard let finalURL = urlComponents.url else {
completion(.failure(.invalidEndpoint))
return
}
urlSession.dataTask(with: finalURL) { [weak self] (data, response, error) in
guard let self = self else { return }
if error != nil {
self.executeNetworkCallback(with: .failure(.apiError), completion: completion)
return
}
guard let httpResponse = response as? HTTPURLResponse, 200..<300 ~= httpResponse.statusCode else {
self.executeNetworkCallback(with: .failure(.invalidResponse), completion: completion)
return
}
guard let data = data else {
self.executeNetworkCallback(with: .failure(.emptyData), completion: completion)
return
}
do {
let decodedResponse = try self.jsonDecoder.decode(D.self, from: data)
self.executeNetworkCallback(with: .success(decodedResponse), completion: completion)
} catch {
self.executeNetworkCallback(with: .failure(.serializationError), completion: completion)
}
}.resume()
}
func executeNetworkCallback<D: Decodable>(
with result: Result<D, NetworkError>,
completion: @escaping (Result<D, NetworkError>) -> ()
) {
DispatchQueue.main.async {
completion(result)
}
}
}
| true
|
9070813911e2893c40400428c487defc2cd60d46
|
Swift
|
rijeqirahma/RRTokpedTest
|
/TokpedTest/Models/ShopTypeModel.swift
|
UTF-8
| 789
| 2.921875
| 3
|
[] |
no_license
|
//
// ShopTypeModel.swift
// TokpedTest
//
// Created by syukur niyadi putra on 18/03/18.
// Copyright © 2018 Jejul. All rights reserved.
//
import Foundation
import UIKit
struct ShopType {
var title : String
}
class ViewShopTypeItem {
private var item : ShopType
var isSelected = true
var title : String {
return item.title
}
init(item : ShopType) {
self.item = item
}
}
class ViewShopType {
var items = [ViewShopTypeItem]()
var selectedItems: [ViewShopTypeItem] {
return items.filter { return $0.isSelected }
}
init() {
items = dataArray.map({ ViewShopTypeItem(item: $0) })
}
let dataArray = [
ShopType(title: "Gold Merchant"),
ShopType(title: "Official Store")]
}
| true
|
a9dc23459872e63a66a24efd3cfd0d839c4c1d78
|
Swift
|
kaitlynwright/Quote-Snacks
|
/Quote Snacks/Quote Snacks/View Controllers/MainViewController.swift
|
UTF-8
| 1,229
| 2.875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Quote Snacks
//
// Created by Kaitlyn Wright on 2/18/19.
// Copyright © 2019 Kaitlyn Wright. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
@IBOutlet weak var mySwitch: UISwitch!
@IBOutlet weak var mainButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if mySwitch.isOn {
// handle on switch
} else {
// handle off switch
}
}
@IBAction func mainButtonPressed(_ sender: UIButton) {
performSegue(withIdentifier: "messageSegue", sender: sender)
}
@IBAction func switchValueChanged(_ sender: UISwitch) {
if sender.isOn {
// handle on switch
/*mainButton.setTitle("Press For Encouragment", for: UIControl.State.normal)
message = " ENCOURAGMENT!! "
face = ":)"*/
} else {
// handle off switch
/*mainButton.setTitle("Press For Discouragment", for: UIControl.State.normal)
message = " DISCOURAGMENT!! "
face = ":("*/
}
}
}
| true
|
730277f2dcdbdff1ca18a10152fb88776d8c1dba
|
Swift
|
AaronM11/PlaceManager_iOS
|
/Place Manager/Place Manager/AddPlaceTableViewController.swift
|
UTF-8
| 3,599
| 2.59375
| 3
|
[] |
no_license
|
//
// AddPlaceTableViewController.swift
// Place Manager
//
// Created by Aaron Musengo on 4/10/18.
// Email: amuseng1@asu.edu
// Copyright © 2018 Aaron Musengo. All rights reserved.
// This software is provided to Arizona State University for the purpose
// of grading and evaluation. This software is provided AS IS.
//
import UIKit
class AddPlaceTableViewController: UITableViewController {
var place: PlaceWrapper?
// MARK: - IBOutlets
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var descriptionTextField: UITextField!
@IBOutlet weak var categoryTextField: UITextField!
@IBOutlet weak var addressTitleTextField: UITextField!
@IBOutlet weak var addressStreetTextField: UITextField!
@IBOutlet weak var elevationTextField: UITextField!
@IBOutlet weak var latitudeTextField: UITextField!
@IBOutlet weak var longitudeTextField: UITextField!
@IBOutlet weak var saveButton: UIBarButtonItem!
//MARK: - Constants
let saveUnwind = "saveUnwind"
override func viewDidLoad() {
super.viewDidLoad()
setupTextField(place: place)
updateSaveButtonState()
}
// MARK: - Private
private func setupTextField(place: PlaceWrapper?) {
guard let place = place else { return }
nameTextField.text = place.name
addressTitleTextField.text = place.addressTitle
addressStreetTextField.text = place.addressStreet
descriptionTextField.text = place.description
categoryTextField.text = place.category
elevationTextField.text = String(place.elevation)
latitudeTextField.text = String(place.latitude)
longitudeTextField.text = String(place.longitude)
}
func updateSaveButtonState() {
let name = nameTextField.text ?? ""
let addressTitle = addressTitleTextField.text ?? ""
let addressStreet = addressStreetTextField.text ?? ""
let description = descriptionTextField.text ?? ""
let category = categoryTextField.text ?? ""
let elevation = elevationTextField.text ?? ""
let latitude = latitudeTextField.text ?? ""
let longitude = longitudeTextField.text ?? ""
saveButton.isEnabled = !name.isEmpty && !addressTitle.isEmpty && !addressStreet.isEmpty && !description.isEmpty && !category.isEmpty && !elevation.isEmpty && !latitude.isEmpty && !longitude.isEmpty
}
@IBAction func textEditingChanged(_ sender: UITextField) {
updateSaveButtonState()
}
override func prepare(for segue: UIStoryboardSegue, sender:
Any?) {
super.prepare(for: segue, sender: sender)
guard segue.identifier == saveUnwind else { return }
let name = nameTextField.text ?? ""
let addressTitle = addressTitleTextField.text ?? ""
let addressStreet = addressStreetTextField.text ?? ""
let description = descriptionTextField.text ?? ""
let category = categoryTextField.text ?? ""
guard let elevationString = elevationTextField.text,
let latitudeString = latitudeTextField.text ,
let longitudeString = longitudeTextField.text else { return }
let elevation = Double(elevationString) ?? 0.0
let latitude = Double(latitudeString) ?? 0.0
let longitude = Double(longitudeString) ?? 0.0
place = PlaceWrapper(name: name, description: description, category: category, addressTitle: addressTitle, addressStreet: addressStreet, elevation: elevation, latitude: latitude, longitude: longitude)
}
}
| true
|
a2fc919603bacfe4e206299baecf53dddbb493fe
|
Swift
|
jjercTK/InFlix
|
/InFlix/File.swift
|
UTF-8
| 1,471
| 2.875
| 3
|
[] |
no_license
|
//
// File.swift
// InFlix
//
// Created by Juanjo on 11/28/16.
// Copyright © 2016 Tektonlabs. All rights reserved.
//
import Foundation
extension NetflixRoulette {
func getMoviesForSearchString(_ search: String, completitionHandlerForMovies:@escaping (_ movies: [Movie]?, _ error: NSError) -> Void) -> URLSessionDataTask {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [NetflixRoulette.ParameterKeys.Director: search]
/* 2. Make the request */
let task = taskForGETMethod(Methods.SearchMovie, parameters: parameters as [String:AnyObject]) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
completionHandlerForMovies(nil, error)
} else {
if let results = results?[TMDBClient.JSONResponseKeys.MovieResults] as? [[String:AnyObject]] {
let movies = TMDBMovie.moviesFromResults(results)
completionHandlerForMovies(movies, nil)
} else {
completionHandlerForMovies(nil, NSError(domain: "getMoviesForSearchString parsing", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not parse getMoviesForSearchString"]))
}
}
}
return task
}
}
| true
|
9a71fd3fff95bb66f9247e4707f46283ac64a540
|
Swift
|
kalebriley/Yhelper
|
/Yhelper/Network/Network.swift
|
UTF-8
| 1,097
| 2.765625
| 3
|
[] |
no_license
|
//
// Network.swift
// Yhelper
//
// Created by Kaleb Riley on 8/1/20.
// Copyright © 2020 tyko9. All rights reserved.
//
import Alamofire
import Foundation
struct Network {
static let shared = Network()
func request<T: Decodable>(target: TargetType, completion: @escaping (Result<T, Error>) -> Void) {
AF.request( target.endpoint(), method: target.method, parameters: target.params, headers: target.headers)
.responseDecodable(of: T.self) { response in
debugPrint(response)
switch response.result {
case .success(let object):
completion(.success(object))
case .failure(let error):
completion(.failure(error))
}
}
}
func request(target: TargetType, completion: (Result<String, Error>) -> Void) {
AF.request( target.endpoint(), method: target.method, parameters: target.params, headers: target.headers)
.responseJSON { resonse in
debugPrint(resonse)
}
}
}
| true
|
736517375ecedcc79c9894fd6a9a218e239f039f
|
Swift
|
JustinEspejo/Snowcialite-Social-Network
|
/Snowcialite iOS App/Login Screen/IntroViewController.swift
|
UTF-8
| 1,367
| 2.5625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Snowcialite iOS App
//
// Created by Justin Espejo on 11/12/15.
// Copyright © 2016 Snowcialite. All rights reserved.
//
import UIKit
class IntroViewController: VideoSplashViewController {
@IBOutlet weak var enterButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setupVideoBackground()
enterButton.backgroundColor = UIColor.whiteColor()
enterButton.layer.cornerRadius = 5.0
enterButton.layer.masksToBounds = true
self.hidesBottomBarWhenPushed = true
self.navigationItem.hidesBackButton = true
enterButton.userInteractionEnabled = true
self.navigationController!.navigationBarHidden = true;
}
@IBAction func enterButtonPressed(sender: AnyObject)
{
navigationController?.popViewControllerAnimated(true)
}
private func setupVideoBackground()
{
let url = NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource("video", ofType: "mov")!)
interaction = false
videoFrame = view.frame
fillMode = .ResizeAspectFill
alwaysRepeat = true
sound = false
startTime = 0
duration = 12.0
alpha = 0.7
backgroundColor = UIColor.blackColor()
contentURL = url
// userInteractionEnabled = false
}
}
| true
|
68c9d4feb9cdd613018b7a1b76dd16c428f32f38
|
Swift
|
realfelixyu/Opinionator
|
/Opinionator/QuizCreation/BucketConfigurationController.swift
|
UTF-8
| 5,014
| 2.734375
| 3
|
[] |
no_license
|
//
// BucketConfigurationController.swift
// Opinionator
//
// Created by Felix Yu on 11/3/20.
// Copyright © 2020 Felix Yu. All rights reserved.
//
import Foundation
import UIKit
protocol BucketDataSaver {
func saveData(data: [Float], answerIndex: Int)
}
class BucketConfigurationController: UIViewController {
var data: [Float]
var bucketNames: [String]
var answerIndex: Int
let questionTitle: String
let answerTitle: String
var delegate: BucketDataSaver?
lazy var sliders: [UISlider] = {
//have to change 4 to bucketNames.count later
var list = [UISlider]()
for i in 0..<bucketNames.count {
list.append(UISlider())
}
return list
}()
lazy var sliderLabels: [UILabel] = {
var list = [UILabel]()
for i in 0..<bucketNames.count {
list.append(UILabel())
}
return list
}()
var scrollView = UIScrollView()
var contentStack: UIStackView = {
var stack = UIStackView()
stack.distribution = .fillProportionally
stack.spacing = 12
stack.axis = .vertical
return stack
}()
//todo will have to calculate height of the label and make it wrap around I think, if the question is too long
lazy var questionTitleLabel: UILabel = {
let label = UILabel()
label.textColor = .black
label.font = UIFont.systemFont(ofSize: 20)
label.text = "Question: \(questionTitle)"
return label
}()
lazy var answerTitleLabel: UILabel = {
let label = UILabel()
label.textColor = .black
label.font = UIFont.systemFont(ofSize: 20)
label.text = "Answer: \(answerTitle)"
return label
}()
init(data: [Float], answerIndex: Int, bucketNames: [String], questionTitle: String, answerTitle: String) {
self.answerIndex = answerIndex
self.data = data
self.bucketNames = bucketNames
self.questionTitle = questionTitle
self.answerTitle = answerTitle
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// view.addSubview(scrollView)
// scrollView.anchor(top: view.safeAreaLayoutGuide.topAnchor, left: view.leftAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, right: view.rightAnchor)
// scrollView.addSubview(contentStack)
// contentStack.anchor(top: scrollView.topAnchor, left: scrollView.leftAnchor, right: view.rightAnchor, paddingTop: 16, paddingLeft: 16, paddingRight: 16)
//
view.addSubview(scrollView)
scrollView.anchor(top: view.safeAreaLayoutGuide.topAnchor, left: view.leftAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, right: view.rightAnchor)
scrollView.addSubview(contentStack)
contentStack.anchor(top: scrollView.topAnchor, left: scrollView.leftAnchor, right: view.rightAnchor, paddingTop: 16, paddingLeft: 16, paddingRight: 16)
configureHeader()
configureSliders()
}
override func viewWillDisappear(_ animated: Bool) {
for i in 0..<bucketNames.count {
// usinng double to store float, should maybe be changed later.
data[i] = sliders[i].value
//print("DEBUG: \(sliders[i].value)")
}
delegate?.saveData(data: data, answerIndex: answerIndex)
}
func configureHeader() {
contentStack.addArrangedSubview(questionTitleLabel)
contentStack.addArrangedSubview(answerTitleLabel)
}
func configureSliders() {
//print("DEBUG \(sliders.count)")
for (index, slider) in sliders.enumerated() {
var label = UILabel()
label.textColor = .black
label.font = UIFont.systemFont(ofSize: 20)
label.text = "Bucket: \(bucketNames[index])"
sliders[index].minimumValue = -100
sliders[index].maximumValue = 100
sliders[index].addTarget(self, action: #selector(handleSliderChange), for: .valueChanged)
sliders[index].isContinuous = true
sliders[index].tag = index
sliders[index].value = data[index]
sliderLabels[index].text = String(sliders[index].value)
sliderLabels[index].font = UIFont.systemFont(ofSize: 18)
sliderLabels[index].textColor = .black
sliderLabels[index].textAlignment = .center
contentStack.addArrangedSubview(label)
contentStack.addArrangedSubview(sliderLabels[index])
contentStack.addArrangedSubview(sliders[index])
}
}
@objc func handleSliderChange(slider: UISlider) {
print("DEBUG: handle slider change")
sliderLabels[slider.tag].text = String(slider.value)
}
}
| true
|
5f032f5eb78178fae8a8f455e6268e43650a5dc4
|
Swift
|
ihusnainalii/my-swift-journey
|
/SwiftUIAirConditionerController/SwiftUIAirConditionerController/View/ModeSelectionView.swift
|
UTF-8
| 1,242
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
//
// ModeSelectionView.swift
// SwiftUIAirConditionerController
//
// Created by Luan Nguyen on 26/12/2020.
//
import SwiftUI
struct ModeSelectionView: View {
@ObservedObject var modeSelector = ModeSelector()
var body: some View {
HStack(spacing: 16) {
ForEach(modeSelector.modes) { mode in
ModeView(mode: mode)
.onTapGesture {
withAnimation {
modeSelector.selectMode(index: mode.id)
}
}
}
}
.foregroundColor(.gray)
.onAppear {
modeSelector.selectMode(index: 0)
}
}
}
struct ModeView: View {
let mode: Mode
var body: some View {
ZStack {
Circle()
.stroke(lineWidth: mode.selected ? 0.0 : 2.0)
.frame(width: 56, height: 56)
Circle()
.fill(mode.selected ? Color.red : Color.clear)
.frame(width: 56, height: 56)
Image(systemName: mode.imageName)
.renderingMode(.template)
.foregroundColor(mode.selected ? .white : .gray)
}
}
}
| true
|
a8636518fccbf7d42246faf78b40c3d46482ed47
|
Swift
|
mikeshep/CapitalSocial
|
/CapitalSocial/Utils/CSPickerDate.swift
|
UTF-8
| 4,293
| 2.53125
| 3
|
[] |
no_license
|
//
// BCPickerDate.swift
// CapitalSocial
//
// Created by Miguel angel olmedo perez on 11/5/18.
// Copyright © 2018 Miguel angel olmedo perez. All rights reserved.
//
import UIKit
public class CSDatePicker {
// MARK:- Attributes
fileprivate var datePicker: UIDatePicker!
fileprivate var toolBar: UIToolbar!
fileprivate var bgView: UIView!
var delegate: CSDatePickerDelegate? = nil
var tag = 0
// MARK:- Methods
func showWith(minDate: Date?,
maxDate: Date?,
andDefaultDate: Date?,
withDateMode: UIDatePicker.Mode?,
andLocale: Locale?) {
let window: UIWindow = UIApplication.shared.delegate!.window!!
let screenSize = UIScreen.main.bounds.size
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.destroyPicker))
bgView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height))
bgView.backgroundColor = CSColor.black
bgView.alpha = 0.0
bgView.addGestureRecognizer(tapGesture)
let pickerFrame = CGRect(x: 0,
y: screenSize.height,
width: screenSize.width,
height: Keys.pickerHeight)
datePicker = UIDatePicker(frame: pickerFrame)
datePicker.timeZone = TimeZone(abbreviation: "UTC")
datePicker.backgroundColor = CSColor.white
datePicker.datePickerMode = .date
if let dateMode = withDateMode {
datePicker.datePickerMode = dateMode
}
if let locale = andLocale {
datePicker.locale = locale
}
if minDate != nil {
datePicker.minimumDate = minDate
} else {
datePicker.minimumDate = Date.newDate(fromYear: 1917, month: 01, day: 01)
}
if maxDate != nil {
datePicker.maximumDate = maxDate
}
if let defaultDate = andDefaultDate,
let minD = minDate,
let maxD = maxDate,
minD <= defaultDate,
defaultDate <= maxD {
datePicker.setDate(defaultDate, animated: true)
}
let btnAcept = UIBarButtonItem(title:" " + CSString.ok,
style: .plain,
target: self,
action: #selector(self.selectItem))
let toolbarFrame = CGRect(x: 0,
y: screenSize.height,
width: screenSize.width,
height: Keys.toolbarHeight)
toolBar = UIToolbar(frame: toolbarFrame)
toolBar.tintColor = CSColor.primaryColor
toolBar.setItems([btnAcept], animated: true)
window.addSubview(bgView)
window.addSubview(toolBar)
window.addSubview(datePicker)
UIView.animate(withDuration: 0.2, animations: {
self.bgView.alpha = 0.5
self.toolBar.frame.origin.y = screenSize.height - (Keys.toolbarHeight + Keys.pickerHeight)
self.datePicker.frame.origin.y = screenSize.height - Keys.pickerHeight
})
}
@objc func selectItem(){
delegate?.onDateSelected(date: datePicker.date, pickerDate: self)
destroyPicker()
}
@objc func destroyPicker(){
UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseIn], animations: {
self.bgView.alpha = 0
}, completion: {(finished) in
self.bgView = nil
})
UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseIn], animations: {
let screenSize = UIScreen.main.bounds.size
self.datePicker.frame.origin.y = screenSize.height
self.toolBar.frame.origin.y = screenSize.height
}, completion: {[weak self] finished in
self?.datePicker = nil
self?.toolBar = nil
})
}
// MARK:- Keys
public struct Keys {
static let pickerHeight = CGFloat(150)
static let toolbarHeight = CGFloat(40)
}
}
protocol CSDatePickerDelegate {
func onDateSelected(date: Date, pickerDate: CSDatePicker)
}
| true
|
c04d5a3c6e2af2b0b4cde66a69bb0f46356e1592
|
Swift
|
qwer810520/Mask_RxSwift-IGListKit
|
/ClinicMaskDemo/Models/Pharmacies.swift
|
UTF-8
| 2,626
| 2.796875
| 3
|
[] |
no_license
|
//
// Pharmacies.swift
// ClinicMaskDemo
//
// Created by Min on 2020/6/11.
// Copyright © 2020 Min. All rights reserved.
//
import Foundation
struct Pharmacies: Decodable {
let id: String
let name: String
let phone: String
let address: String
let available: String
let maskAdult: Int
let maskChild: Int
let updated: String
let note: String
let customNote: String
let website: String
let county: String
let town: String
let cunli: String
let servicePeriods: String
let coordinates: [Double]
enum BaseKeys: String, CodingKey {
case properties, geometry
}
enum PropertiesKeys: String, CodingKey {
case id, name, phone, address, mask_adult, mask_child, updated, available, note, custom_note, website, county, town, cunli, service_periods
}
enum GeometryKeys: String, CodingKey {
case coordinates
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: BaseKeys.self)
let pharmaciesInfo = try values.nestedContainer(keyedBy: PropertiesKeys.self, forKey: .properties)
self.id = try pharmaciesInfo.decodeIfPresent(String.self, forKey: .id) ?? ""
self.name = try pharmaciesInfo.decodeIfPresent(String.self, forKey: .name) ?? ""
self.phone = try pharmaciesInfo.decodeIfPresent(String.self, forKey: .phone) ?? ""
self.address = try pharmaciesInfo.decodeIfPresent(String.self, forKey: .address) ?? ""
self.available = try pharmaciesInfo.decodeIfPresent(String.self, forKey: .available) ?? ""
self.maskAdult = try pharmaciesInfo.decodeIfPresent(Int.self, forKey: .mask_adult) ?? 0
self.maskChild = try pharmaciesInfo.decodeIfPresent(Int.self, forKey: .mask_child) ?? 0
self.updated = try pharmaciesInfo.decodeIfPresent(String.self, forKey: .updated) ?? ""
self.note = try pharmaciesInfo.decodeIfPresent(String.self, forKey: .note) ?? ""
self.customNote = try pharmaciesInfo.decodeIfPresent(String.self, forKey: .custom_note) ?? ""
self.website = try pharmaciesInfo.decodeIfPresent(String.self, forKey: .website) ?? ""
self.county = try pharmaciesInfo.decodeIfPresent(String.self, forKey: .county) ?? ""
self.town = try pharmaciesInfo.decodeIfPresent(String.self, forKey: .town) ?? ""
self.cunli = try pharmaciesInfo.decodeIfPresent(String.self, forKey: .cunli) ?? ""
self.servicePeriods = try pharmaciesInfo.decodeIfPresent(String.self, forKey: .service_periods) ?? ""
let geometryInfo = try values.nestedContainer(keyedBy: GeometryKeys.self, forKey: .geometry)
self.coordinates = try geometryInfo.decodeIfPresent([Double].self, forKey: .coordinates) ?? []
}
}
| true
|
7d76aacf98586930f5797d342200b253d31ab757
|
Swift
|
algolia/algoliasearch-client-swift
|
/Sources/AlgoliaSearchClient/Models/Search/Query/Auxiliary/AroundPrecision.swift
|
UTF-8
| 734
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
//
// AroundPrecision.swift
//
//
// Created by Vladislav Fitc on 23/03/2020.
//
import Foundation
public struct AroundPrecision: Codable, Equatable {
public let from: Int
public let value: Int
public init(from: Int, value: Int) {
self.from = from
self.value = value
}
}
extension AroundPrecision: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self.from = 0
self.value = value
}
}
extension AroundPrecision: ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) {
self.from = 0
self.value = Int(value)
}
}
extension AroundPrecision: URLEncodable {
public var urlEncodedString: String {
return "{\"from\":\(from),\"value\":\(value)}"
}
}
| true
|
56ec9f5a13117782558b6ed6fc327ad513fc8cf0
|
Swift
|
yadudoc/swift-hadoop
|
/hadoop_coasters/test/test.swift
|
UTF-8
| 312
| 2.546875
| 3
|
[] |
no_license
|
type file;
app (file o, file e) test (){
python "-c" "print(\"Hello\")" stdout=@o stderr=@e;
}
app (file o, file e) test2 (file f){
cat @f stdout=@o stderr=@e;
}
file out <"hi.out">;
file err <"hi.err">;
file out2 <"cat.out">;
file err2 <"cat.err">;
(out, err) = test();
(out2, err2) = test2(out);
| true
|
35a737aa1c1a05d8b8d4e15394501b622bd3e022
|
Swift
|
wilsondivino/MtgApp
|
/MtgApp/EdicoesMtg.swift
|
UTF-8
| 480
| 2.609375
| 3
|
[] |
no_license
|
//
// EdicoesMtg.swift
// MtgApp
//
// Created by Wilson Divino on 13/12/15.
// Copyright © 2015 Wilson Divino. All rights reserved.
//
import Foundation
class EdicoesMtg {
var nome : String = ""
var codigo : String = ""
init( nome : String, codigo : String ){
self.nome = nome
self.codigo = codigo
}
func getNome() -> String {
return self.nome
}
func getCodigo() -> String {
return self.codigo
}
}
| true
|
c9b24556d720bf70f5deb9d3c55ea19d67d7cb08
|
Swift
|
iMaxiOS/SearchPhoto
|
/SearchPhoto/Controllers/SearchResults.swift
|
UTF-8
| 474
| 2.765625
| 3
|
[] |
no_license
|
//
// SearchResults.swift
// SearchPhoto
//
// Created by Maxim Granchenko on 28.01.2020.
// Copyright © 2020 Maxim Granchenko. All rights reserved.
//
import Foundation
// MARK: - Result
struct SearchResults: Decodable {
let total: Int
let results: [UnsplashPhoto]
}
// MARK: - Photo
struct UnsplashPhoto: Decodable {
let width, height: Int
let urls: [URLKing.RawValue: String]
enum URLKing: String {
case raw, full, regular, small, thumb
}
}
| true
|
736ddae43a4438cc206fb81e9b7af6cefa325415
|
Swift
|
wangyqGitHub/TNWaterFallListView
|
/RxWaterfallLayoutCollectionView/RxWaterfallLayoutCollectionView/swift_CHTCollectionViewWaterfallLayout/CHTCollectionViewWaterfallLayout.swift
|
UTF-8
| 32,757
| 2.96875
| 3
|
[] |
no_license
|
//
// CHTCollectionViewWaterfallLayout.swift
// RxWaterfallLayoutCollectionView
//
// Created by 张灿 on 2017/6/7.
// Copyright © 2017年 FDD. All rights reserved.
//
import UIKit
/**
* Enumerated structure to define direction in which items can be rendered.
*/
public enum CHTCollectionViewWaterfallLayoutItemRenderDirection {
case shortestFirst
case leftToRight
case rightToLeft
}
/**
* Constants that specify the types of supplementary views that can be presented using a waterfall layout.
*/
public struct CHTCollectionElementKind {
/// A supplementary view that identifies the header for a given section.
static let sectionHeader = "CHTCollectionElementKindSectionHeader"
/// A supplementary view that identifies the footer for a given section.
static let sectionFooter = "CHTCollectionElementKindSectionFooter"
}
// MARK: - CHTCollectionViewWaterfallLayout
public class CHTCollectionViewWaterfallLayout: UICollectionViewLayout {
/**
* @brief sectionHeaderStyle
* @discussion Default: group
*/
public enum Style {
case group
case plain
}
public var style = Style.plain {
didSet {
if style != oldValue {
self.invalidateLayout()
}
}
}
/**
* @brief How many columns for this layout.
* @discussion Default: 2
*/
public var columnCount = 2 {
didSet {
if columnCount != oldValue {
self.invalidateLayout()
}
}
}
/**
* @brief The minimum spacing to use between successive columns.
* @discussion Default: 10.0
*/
public var minimumColumnSpacing: CGFloat = 10.0 {
didSet {
if minimumColumnSpacing != oldValue {
self.invalidateLayout()
}
}
}
/**
* @brief The minimum spacing to use between items in the same column.
* @discussion Default: 10.0
* @note This spacing is not applied to the space between header and columns or between columns and footer.
*/
public var minimumInteritemSpacing: CGFloat = 10.0 {
didSet {
if minimumInteritemSpacing != oldValue {
self.invalidateLayout()
}
}
}
/**
* @brief Height for section header
* @discussion
* If your collectionView's delegate doesn't implement `collectionView:layout:heightForHeaderInSection:`,
* then this value will be used.
*
* Default: 0
*/
public var headerHeight: CGFloat = 0.0 {
didSet {
if headerHeight != oldValue {
self.invalidateLayout()
}
}
}
/**
* @brief Height for section footer
* @discussion
* If your collectionView's delegate doesn't implement `collectionView:layout:heightForFooterInSection:`,
* then this value will be used.
*
* Default: 0
*/
public var footerHeight: CGFloat = 0.0 {
didSet {
if footerHeight != oldValue {
self.invalidateLayout()
}
}
}
/**
* @brief The margins that are used to lay out the header for each section.
* @discussion
* These insets are applied to the headers in each section.
* They represent the distance between the top of the collection view and the top of the content items
* They also indicate the spacing on either side of the header. They do not affect the size of the headers or footers themselves.
*
* Default: UIEdgeInsetsZero
*/
public var headerInset = UIEdgeInsets.zero {
didSet {
if headerInset != oldValue {
self.invalidateLayout()
}
}
}
/**
* @brief The margins that are used to lay out the footer for each section.
* @discussion
* These insets are applied to the footers in each section.
* They represent the distance between the top of the collection view and the top of the content items
* They also indicate the spacing on either side of the footer. They do not affect the size of the headers or footers themselves.
*
* Default: UIEdgeInsetsZero
*/
public var footerInset = UIEdgeInsets.zero {
didSet {
if footerInset != oldValue {
self.invalidateLayout()
}
}
}
/**
* @brief The margins that are used to lay out content in each section.
* @discussion
* Section insets are margins applied only to the items in the section.
* They represent the distance between the header view and the columns and between the columns and the footer view.
* They also indicate the spacing on either side of columns. They do not affect the size of the headers or footers themselves.
*
* Default: UIEdgeInsetsZero
*/
public var sectionInset = UIEdgeInsets.zero {
didSet {
if sectionInset != oldValue {
self.invalidateLayout()
}
}
}
/**
* @brief The direction in which items will be rendered in subsequent rows.
* @discussion
* The direction in which each item is rendered. This could be left to right (CHTCollectionViewWaterfallLayoutItemRenderDirectionLeftToRight), right to left (CHTCollectionViewWaterfallLayoutItemRenderDirectionRightToLeft), or shortest column fills first (CHTCollectionViewWaterfallLayoutItemRenderDirectionShortestFirst).
*
* Default: CHTCollectionViewWaterfallLayoutItemRenderDirectionShortestFirst
*/
public var itemRenderDirection = CHTCollectionViewWaterfallLayoutItemRenderDirection.shortestFirst {
didSet {
if itemRenderDirection != oldValue {
self.invalidateLayout()
}
}
}
/**
* @brief The minimum height of the collection view's content.
* @discussion
* The minimum height of the collection view's content. This could be used to allow hidden headers with no content.
*
* Default: 0.f
*/
public var minimumContentHeight: CGFloat = 0.0 {
didSet {
if minimumContentHeight != oldValue {
self.invalidateLayout()
}
}
}
/**
* @brief The calculated width of an item in the specified section.
* @discussion
* The width of an item is calculated based on number of columns, the collection view width, and the horizontal insets for that section.
*/
public func itemWidth(InSectionAtIndex section: Int) -> CGFloat {
guard let collectionView = collectionView else {
return 0
}
let sectionInset = self.delegate?.collectView(collectionView, layout: self, insetForSectionAtIndex: section) ?? self.sectionInset
let width = collectionView.bounds.size.width - sectionInset.left - sectionInset.right
let columnCount = self.columnCount(section: section)
let columnSpacing = self.delegate?.collectView(collectionView, layout: self, minimumColumnSpacingForSectionAtIndex: section) ?? self.minimumColumnSpacing
return CHTCollectionViewWaterfallLayout.CHTFloor((width - CGFloat(columnCount - 1) * columnSpacing) / CGFloat(columnCount))
}
/// How many items to be union into a single rectangle
fileprivate static let unionSize = 20
/// The delegate will point to collection view's delegate automatically.
fileprivate weak var delegate: CHTCollectionViewDelegateWaterfallLayout? {
return (self.collectionView?.delegate as? CHTCollectionViewDelegateWaterfallLayout)
}
/// Array to store height for each column
fileprivate var columnHeights = [[CGFloat]]()
/// Array of arrays. Each array stores item attributes for each section
fileprivate var sectionItemAttributes = [[UICollectionViewLayoutAttributes]]()
/// Array to store attributes for all items includes headers, cells, and footers
fileprivate var allItemAttributes = [UICollectionViewLayoutAttributes]()
/// Dictionary to store section headers' attribute
fileprivate var headersAttribute = [Int: UICollectionViewLayoutAttributes]()
/// Dictionary to store section footers' attribute
fileprivate var footersAttribute = [Int: UICollectionViewLayoutAttributes]()
/// Array to store union rectangles
fileprivate var unionRects = [CGRect]()
/// Array to store a sectionHeaderStick rectangles, for compute HeaderStick
fileprivate var headerStickRectangles = [CGRect]()
fileprivate var fromHederStickChange = false
}
extension CHTCollectionViewWaterfallLayout {
fileprivate static func CHTFloor(_ value: CGFloat) -> CGFloat {
let scale = UIScreen.main.scale
return floor(value * scale) / scale
}
fileprivate func columnCount(section: Int) -> Int {
guard let collectionView = collectionView,
let delegate = delegate else {
return self.columnCount
}
return delegate.collectView(collectionView, layout: self, columnCountForSection: section)
}
//MARK: - Methods to Override
public override func prepare() {
super.prepare()
if fromHederStickChange == false {
headersAttribute.removeAll()
footersAttribute.removeAll()
unionRects.removeAll()
columnHeights.removeAll()
allItemAttributes.removeAll()
sectionItemAttributes.removeAll()
headerStickRectangles.removeAll()
guard let collectionView = collectionView else { return }
guard let numberOfSections = self.collectionView?.numberOfSections,
numberOfSections > 0 else {
return
}
for section in 0..<numberOfSections {
let columnCount = self.columnCount(section: section)
let sectionColumnHeights = Array<CGFloat>(repeating: 0, count: columnCount)
columnHeights.append(sectionColumnHeights)
}
// Create attributes
var top: CGFloat = 0
for section in 0..<numberOfSections {
/*
* 1. Get section-specific metrics (minimumInteritemSpacing, sectionInset)
*/
let minimumInteritemSpacing = self.delegate?.collectView(collectionView, layout: self, minimumInteritemSpacingForSectionAtIndex: section) ?? self.minimumInteritemSpacing
let columnSpacing = self.delegate?.collectView(collectionView, layout: self, minimumColumnSpacingForSectionAtIndex: section) ?? self.minimumColumnSpacing
let sectionInset = self.delegate?.collectView(collectionView, layout: self, insetForSectionAtIndex: section) ?? self.sectionInset
let width = collectionView.bounds.width - sectionInset.left - sectionInset.right
let columnCount = self.columnCount(section: section)
let itemWidth = CHTCollectionViewWaterfallLayout.CHTFloor((width - (CGFloat(columnCount) - 1) * columnSpacing) / CGFloat(columnCount))
/*
* 2. Section header
*/
let headerHeight = self.delegate?.collectView(collectionView, layout: self, heightForHeaderInSection: section) ?? self.headerHeight
let headerInset = self.delegate?.collectView(collectionView, layout: self, insetForHeaderInSection: section) ?? self.headerInset
top += headerInset.top
var sectionRect = CGRect(x: 0,
y: top,
width: collectionView.bounds.width,
height: 0)
if headerHeight > 0 {
let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: CHTCollectionElementKind.sectionHeader, with: IndexPath(row: 0, section: section))
attributes.frame = CGRect(x: headerInset.left,
y: top,
width: collectionView.bounds.width - headerInset.left - headerInset.right,
height: headerHeight)
self.headersAttribute[section] = attributes
self.allItemAttributes.append(attributes)
top = attributes.frame.maxY + headerInset.bottom
}
top += sectionInset.top
for index in 0..<columnCount {
self.columnHeights[section][index] = top
}
/*
* 3. Section items
*/
let itemCount = collectionView.numberOfItems(inSection: section)
var itemAttributes = [UICollectionViewLayoutAttributes]()
for index in 0 ..< itemCount {
let indexPath = IndexPath(row: index, section: section)
let columnIndex = nextColumnIndex(itemIndexPath: indexPath)
let xOffset = sectionInset.left + (itemWidth + columnSpacing) * CGFloat(columnIndex)
let yOffset = self.columnHeights[section][columnIndex]
let itemSize = self.delegate?.collectView(collectionView, layout: self, sizeForItemAtIndexPath: indexPath) ?? .zero
var itemHeight: CGFloat = 0
if itemSize.width > 0 && itemSize.height > 0 {
itemHeight = CHTCollectionViewWaterfallLayout.CHTFloor(itemSize.height * itemWidth / itemSize.width)
}
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(x: xOffset,
y: yOffset,
width: itemWidth,
height: itemHeight)
itemAttributes.append(attributes)
self.allItemAttributes.append(attributes)
self.columnHeights[section][columnIndex] = attributes.frame.maxY + minimumInteritemSpacing
}
self.sectionItemAttributes.append(itemAttributes)
/*
* 4. Section footer
*/
let columnIndex = longestColumnIndex(inSection: section)
if self.columnHeights[section].count > 0 {
top = self.columnHeights[section][columnIndex] - minimumInteritemSpacing + sectionInset.bottom
} else {
top = 0
}
let footerHeight = self.delegate?.collectView(collectionView, layout: self, heightForFooterInSection: section) ?? self.footerHeight
let footerInset = self.delegate?.collectView(collectionView, layout: self, insetForFooterInSection: section) ?? self.footerInset
top += footerInset.top
if footerHeight > 0 {
let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: CHTCollectionElementKind.sectionFooter, with: IndexPath(row: 0, section: section))
attributes.frame = CGRect(x: footerInset.left,
y: top,
width: collectionView.bounds.width - footerInset.left - footerInset.right,
height: footerHeight)
self.footersAttribute[section] = attributes
self.allItemAttributes.append(attributes)
top = attributes.frame.maxY + footerInset.bottom
}
for index in 0..<columnCount {
self.columnHeights[section][index] = top
}
/*
* 5. compute Section headerStickRectangle
*/
sectionRect = CGRect(x: sectionRect.minX,
y: sectionRect.minY,
width: sectionRect.width,
height: top - sectionRect.minY)
headerStickRectangles.append(sectionRect)
}// end of for for section in 0..<numberOfSections
// Build union rects
var index = 0
let itemCount = self.allItemAttributes.count
while index < itemCount {
var unionRect = self.allItemAttributes[index].frame
let rectEndIndex = min(index + CHTCollectionViewWaterfallLayout.unionSize, itemCount)
for i in (index + 1)..<(rectEndIndex) {
unionRect = unionRect.union(self.allItemAttributes[i].frame)
}
index = rectEndIndex
self.unionRects.append(unionRect)
}
} else {
fromHederStickChange = false
}
}
public override var collectionViewContentSize: CGSize {
guard let collectionView = collectionView else {
return .zero
}
let numberOfSections = collectionView.numberOfSections
if numberOfSections == 0 {
return .zero
}
var contentSize = collectionView.bounds.size
contentSize.height = self.columnHeights.last?.first ?? 0
if contentSize.height < self.minimumContentHeight {
contentSize.height = self.minimumContentHeight
}
return contentSize
}
public override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if indexPath.section >= self.sectionItemAttributes.count {
return nil
}
if indexPath.item >= self.sectionItemAttributes[indexPath.section].count {
return nil
}
return self.sectionItemAttributes[indexPath.section][indexPath.item]
}
public override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
switch elementKind {
case CHTCollectionElementKind.sectionHeader:
return self.headersAttribute[indexPath.section]
case CHTCollectionElementKind.sectionFooter:
return self.footersAttribute[indexPath.section]
default:
return nil
}
}
public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var begin = 0
var end = self.unionRects.count
for i in 0..<self.unionRects.count {
if rect.intersects(self.unionRects[i]) {
begin = i * CHTCollectionViewWaterfallLayout.unionSize
break
}
}
for i in (0..<self.unionRects.count).reversed() {
if rect.intersects(self.unionRects[i]) {
end = min((i + 1) * CHTCollectionViewWaterfallLayout.unionSize, self.allItemAttributes.count)
break
}
}
var result = [UICollectionViewLayoutAttributes]()
for i in begin..<end {
let attr = self.allItemAttributes[i]
if rect.intersects(attr.frame) {
result.append(attr)
}
}
return result
}
public override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
let oldRect = collectionView?.bounds ?? .zero
if style == .plain {
if newBounds != oldRect {
sectionHeaderStickCounter(in: newBounds)
fromHederStickChange = true
return true
}
} else {
if newBounds.width != oldRect.width {
return true
}
}
return false
}
// MARK: - private Method
fileprivate func sectionHeaderStickCounter(in rect: CGRect) {
let starPoint = CGPoint(x: rect.minX + 1, y: rect.minY + 1)
var sectionRect: CGRect? = nil
for frameItem in headerStickRectangles {
if frameItem.contains(starPoint) {
sectionRect = frameItem
break
}
}
guard let curRect = sectionRect else {
return
}
var stickHeader: UICollectionViewLayoutAttributes? = nil
for attribute in self.headersAttribute.values {
attribute.transform = .identity
if curRect.contains(attribute.frame) {
stickHeader = attribute
}
}
if let header = stickHeader {
header.zIndex = 1024
let intersectionRect = curRect.intersection(rect)
if intersectionRect.height >= header.frame.height {
header.transform = CGAffineTransform.identity
.translatedBy(x: intersectionRect.minX - header.frame.minX,
y: intersectionRect.minY - header.frame.minY)
} else {
header.transform = CGAffineTransform.identity
.translatedBy(x: intersectionRect.minX - header.frame.minX,
y: (intersectionRect.maxY - header.frame.height) - header.frame.minY)
}
}
print("rect:\(rect)")
print("curRect:\(curRect)")
}
fileprivate func nextColumnIndex(itemIndexPath: IndexPath) -> Int {
var index = 0
let columnCount = self.columnCount(section: itemIndexPath.section)
switch itemRenderDirection {
case .shortestFirst:
index = shortestColumnIndex(inSection: itemIndexPath.section)
case .leftToRight:
index = itemIndexPath.item % columnCount
case .rightToLeft:
index = (columnCount - 1) - (itemIndexPath.item % columnCount)
}
return index
}
fileprivate func shortestColumnIndex(inSection section: Int) -> Int {
var index = 0
var shortestHeight: CGFloat = CGFloat.greatestFiniteMagnitude
for itemIndex in 0..<self.columnHeights[section].count {
let height = self.columnHeights[section][itemIndex]
if height < shortestHeight {
shortestHeight = height
index = itemIndex
}
}
return index
}
fileprivate func longestColumnIndex(inSection section: Int) -> Int {
var index = 0
var longestHeight: CGFloat = 0
for itemIndex in 0..<self.columnHeights[section].count {
let height = self.columnHeights[section][itemIndex]
if height > longestHeight {
longestHeight = height
index = itemIndex
}
}
return index
}
}
// MARK: - CHTCollectionViewDelegateWaterfallLayout
/**
* The CHTCollectionViewDelegateWaterfallLayout protocol defines methods that let you coordinate with a
* CHTCollectionViewWaterfallLayout object to implement a waterfall-based layout.
* The methods of this protocol define the size of items.
*
* The waterfall layout object expects the collection view’s delegate object to adopt this protocol.
* Therefore, implement this protocol on object assigned to your collection view’s delegate property.
*/
public protocol CHTCollectionViewDelegateWaterfallLayout: UICollectionViewDelegate {
/**
* Asks the delegate for the size of the specified item’s cell.
*
* @param collectionView
* The collection view object displaying the waterfall layout.
* @param collectionViewLayout
* The layout object requesting the information.
* @param indexPath
* The index path of the item.
*
* @return
* The original size of the specified item. Both width and height must be greater than 0.
*/
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, sizeForItemAtIndexPath indexPath:IndexPath ) -> CGSize
/**
* Asks the delegate for the column count in a section
*
* @param collectionView
* The collection view object displaying the waterfall layout.
* @param collectionViewLayout
* The layout object requesting the information.
* @param section
* The section.
*
* @return
* The original column count for that section. Must be greater than 0.
*/
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, columnCountForSection section:Int ) -> Int
/**
* Asks the delegate for the height of the header view in the specified section.
*
* @param collectionView
* The collection view object displaying the waterfall layout.
* @param collectionViewLayout
* The layout object requesting the information.
* @param section
* The index of the section whose header size is being requested.
*
* @return
* The height of the header. If you return 0, no header is added.
*
* @discussion
* If you do not implement this method, the waterfall layout uses the value in its headerHeight property to set the size of the header.
*
* @see
* headerHeight
*/
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, heightForHeaderInSection section:Int ) -> CGFloat
/**
* Asks the delegate for the height of the footer view in the specified section.
*
* @param collectionView
* The collection view object displaying the waterfall layout.
* @param collectionViewLayout
* The layout object requesting the information.
* @param section
* The index of the section whose header size is being requested.
*
* @return
* The height of the footer. If you return 0, no footer is added.
*
* @discussion
* If you do not implement this method, the waterfall layout uses the value in its footerHeight property to set the size of the footer.
*
* @see
* footerHeight
*/
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, heightForFooterInSection section:Int ) -> CGFloat
/**
* Asks the delegate for the insets in the specified section.
*
* @param collectionView
* The collection view object displaying the waterfall layout.
* @param collectionViewLayout
* The layout object requesting the information.
* @param section
* The index of the section whose insets are being requested.
*
* @discussion
* If you do not implement this method, the waterfall layout uses the value in its sectionInset property.
*
* @return
* The insets for the section.
*/
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, insetForSectionAtIndex section:Int ) -> UIEdgeInsets
/**
* Asks the delegate for the header insets in the specified section.
*
* @param collectionView
* The collection view object displaying the waterfall layout.
* @param collectionViewLayout
* The layout object requesting the information.
* @param section
* The index of the section whose header insets are being requested.
*
* @discussion
* If you do not implement this method, the waterfall layout uses the value in its headerInset property.
*
* @return
* The headerInsets for the section.
*/
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, insetForHeaderInSection section:Int ) -> UIEdgeInsets
/**
* Asks the delegate for the footer insets in the specified section.
*
* @param collectionView
* The collection view object displaying the waterfall layout.
* @param collectionViewLayout
* The layout object requesting the information.
* @param section
* The index of the section whose footer insets are being requested.
*
* @discussion
* If you do not implement this method, the waterfall layout uses the value in its footerInset property.
*
* @return
* The footerInsets for the section.
*/
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, insetForFooterInSection section:Int ) -> UIEdgeInsets
/**
* Asks the delegate for the minimum spacing between two items in the same column
* in the specified section. If this method is not implemented, the
* minimumInteritemSpacing property is used for all sections.
*
* @param collectionView
* The collection view object displaying the waterfall layout.
* @param collectionViewLayout
* The layout object requesting the information.
* @param section
* The index of the section whose minimum interitem spacing is being requested.
*
* @discussion
* If you do not implement this method, the waterfall layout uses the value in its minimumInteritemSpacing property to determine the amount of space between items in the same column.
*
* @return
* The minimum interitem spacing.
*/
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, minimumInteritemSpacingForSectionAtIndex section:Int ) -> CGFloat
/**
* Asks the delegate for the minimum spacing between colums in a secified section. If this method is not implemented, the
* minimumColumnSpacing property is used for all sections.
*
* @param collectionView
* The collection view object displaying the waterfall layout.
* @param collectionViewLayout
* The layout object requesting the information.
* @param section
* The index of the section whose minimum interitem spacing is being requested.
*
* @discussion
* If you do not implement this method, the waterfall layout uses the value in its minimumColumnSpacing property to determine the amount of space between columns in each section.
*
* @return
* The minimum spacing between each column.
*/
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, minimumColumnSpacingForSectionAtIndex section:Int ) -> CGFloat
}
public extension CHTCollectionViewDelegateWaterfallLayout {
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, columnCountForSection section:Int ) -> Int {
return collectionViewLayout.columnCount
}
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, heightForHeaderInSection section:Int ) -> CGFloat {
return collectionViewLayout.headerHeight
}
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, heightForFooterInSection section:Int ) -> CGFloat {
return collectionViewLayout.footerHeight
}
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, insetForSectionAtIndex section:Int ) -> UIEdgeInsets {
return collectionViewLayout.sectionInset
}
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, insetForHeaderInSection section:Int ) -> UIEdgeInsets {
return collectionViewLayout.headerInset
}
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, insetForFooterInSection section:Int ) -> UIEdgeInsets {
return collectionViewLayout.footerInset
}
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, minimumInteritemSpacingForSectionAtIndex section:Int ) -> CGFloat {
return collectionViewLayout.minimumInteritemSpacing
}
func collectView(_ collectView:UICollectionView, layout collectionViewLayout: CHTCollectionViewWaterfallLayout, minimumColumnSpacingForSectionAtIndex section:Int ) -> CGFloat {
return collectionViewLayout.minimumColumnSpacing
}
}
| true
|
b123fa7c739b3ddf689cd488ef736b01569fbe0c
|
Swift
|
AbhinavVerma0012/MBTA
|
/MBTA/MBTA/Manager/APIManager.swift
|
UTF-8
| 4,210
| 2.828125
| 3
|
[] |
no_license
|
//
// APIManager.swift
// MBTA
//
// Created by Abhinav Verma on 18/02/20.
// Copyright © 2020 Abhinav Verma. All rights reserved.
//
import Foundation
import UIKit
class APIManager{
static let manager = APIManager()
static var commodities = [Commodity]()
static var price = Price()
static var notices = Notice()
static var ads = [Datum]()
private init(){
}
func fetchAPIData(urlString: String, completion: @escaping (Data?,Bool)->Void){
let url = URL(string: urlString)
guard let validUrl = url else {return}
let request = URLRequest(url: validUrl)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let _ = error{
completion(nil,false)
} else {
completion(data,true)
}
}
task.resume()
}
func parseCommoditiesData(data: Data?, success: Bool){
if success{
let decoder = JSONDecoder()
do{
let commodities = try decoder.decode(Commodities.self, from: data!)
APIManager.commodities = commodities.rows ?? [Commodity]()
}
catch(let error){
print(error.localizedDescription)
}
}
}
func parsePriceData(data: Data?, success: Bool){
if success{
let decoder = JSONDecoder()
do{
let price = try decoder.decode(Price.self, from: data!)
APIManager.price = price
}
catch(let error){
print(error.localizedDescription)
}
}
}
func parseNoticeData(data: Data?, success: Bool){
if success{
let decoder = JSONDecoder()
do{
let noticeboard = try decoder.decode(Noticeboard.self, from: data!)
APIManager.notices = noticeboard.data!
}
catch(let error){
print(error.localizedDescription)
}
}
}
func parseAdsData(data: Data?, success: Bool){
if success{
let decoder = JSONDecoder()
do{
let ads = try decoder.decode(Advertisements.self, from: data!)
for value in ads.data.values{
APIManager.ads += value
}
}
catch(let error){
print(error.localizedDescription)
}
}
}
func fetchCommodities(completion: @escaping (Bool)->Void){
fetchAPIData(urlString: commodityRateURL) { (data, success) in
self.parseCommoditiesData(data: data, success: success)
completion(success)
}
}
func fetchPrices(completion: @escaping (Bool)->Void){
fetchAPIData(urlString: baseURL+mrtRateUrl) { (data, success) in
self.parsePriceData(data: data, success: success)
completion(success)
}
}
func fetchNotices(completion: @escaping (Bool)->Void){
fetchAPIData(urlString: baseURL+noticeboardUrl) { (data, success) in
self.parseNoticeData(data: data, success: success)
completion(success)
}
}
func fetchAds(completion: @escaping (Bool)->Void){
fetchAPIData(urlString: baseURL+adsUrl) { (data, success) in
self.parseAdsData(data: data, success: success)
completion(success)
}
}
func fetchData(completion: @escaping (Bool)->Void){
fetchCommodities { (success) in
if success{
self.fetchPrices { (success) in
if success{
self.fetchNotices { (success) in
if success{
completion(true)
}
}
}
}
}
}
}
}
| true
|
17112fb73a148341874197e1727a5707b5c3600b
|
Swift
|
bebone/Medit
|
/Medit/CarnetViewController.swift
|
UTF-8
| 5,917
| 2.609375
| 3
|
[] |
no_license
|
//
// CarnetViewController.swift
// Medit
//
// Created by ANAIS VIDAL on 20/01/2017.
// Copyright © 2017 ANAIS VIDAL. All rights reserved.
//
import UIKit
class CarnetViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,UIGestureRecognizerDelegate {
/* INFO : renommage de Carnet en Journal de bord */
var cellsFichier = [String]() //Création d'un tableau string vide pour manipulation
var cellsUrlFichier = [URL]()
var nombreCells:Int = 0
@IBOutlet weak var carnetTableview: UITableView!
@IBOutlet weak var contenuArticleTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title="Journal de bord"
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(CarnetViewController.handleLongPress(_:)))
lpgr.minimumPressDuration = 0.5 //appuie plus de 0.5s
lpgr.delaysTouchesBegan = true
lpgr.delegate = self
self.carnetTableview.addGestureRecognizer(lpgr)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
carnetTableview.reloadData() // on rafraichit la liste
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
// récupération des URL des fichiers txt stockés dans l'app
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
print(directoryContents)
let txtFiles = directoryContents.filter{ $0.pathExtension == "txt" }
print("txt urls:",txtFiles)
cellsUrlFichier = txtFiles //on sauvegarde les urls (on l'affiche pas)
let txtFileNames = txtFiles.map{ $0.deletingPathExtension().lastPathComponent }
print("txt list:", txtFileNames)
nombreCells = txtFileNames.count //nombre de cellule dans la tableView
cellsFichier=txtFileNames //Population du tableau créé précedemment
//
} catch let error as NSError {
print(error.localizedDescription)
}
return nombreCells
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->UITableViewCell
{
let cell = UITableViewCell(style:UITableViewCellStyle.default , reuseIdentifier: "cell")
//Injection des valeurs du tableau dans les cellules
cell.textLabel?.text = cellsFichier[indexPath.row]
return(cell)
}
public func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let row = indexPath.row
//print(cellsUrlFichier[row]) //Debug
let fileURL = cellsUrlFichier[row]
var inString = ""
do {
inString = try String(contentsOf: fileURL)
} catch {
print("Impossible de lire l' URL: \(fileURL), Error: " + error.localizedDescription)
}
//print("Read from file: \(inString)") //Debug
contenuArticleTextView.text = inString
}
func handleLongPress(_ gestureReconizer: UILongPressGestureRecognizer) {
if gestureReconizer.state != UIGestureRecognizerState.ended {
return
}
let p = gestureReconizer.location(in: carnetTableview)
let indexPath = carnetTableview.indexPathForRow(at: p)
if let index = indexPath {
_ = carnetTableview.cellForRow(at: index)
let alertDelete = UIAlertController(title: "Supprimer", message: "Etes vous sûr de vouloir supprimer l'article "+cellsFichier[index.row]+"?", preferredStyle: UIAlertControllerStyle.alert)
alertDelete.addAction(UIAlertAction(title: "Oui", style: .default, handler: { (action: UIAlertAction!) in
print("Debug")
self.deleteArticle(itemName: self.cellsFichier[index.row], fileExtension: "txt")
}))
alertDelete.addAction(UIAlertAction(title: "Retour", style: UIAlertActionStyle.default, handler: nil))
self.present(alertDelete, animated: true, completion: nil)
} else {
print("Could not find index path")
}
}
func deleteArticle(itemName:String, fileExtension: String) {
//avec l'aide de http://stackoverflow.com/questions/15017902/delete-specified-file-from-document-directory#15018209
let fileManager = FileManager.default
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
guard let dirPath = paths.first else {
return
}
let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
do {
try fileManager.removeItem(atPath: filePath)
let alertDeleteSuccess = UIAlertController(title: "Supprimé !", message: "Article supprimé !", preferredStyle: UIAlertControllerStyle.alert)
alertDeleteSuccess.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alertDeleteSuccess, animated: true, completion: nil)
contenuArticleTextView.text = "Choisissez un contenu dans la liste"
viewWillAppear(true)
} catch let error as NSError {
print(error.debugDescription)
}}
}
| true
|
ae638ac9ced154657e86a17a146640d4618a58ff
|
Swift
|
MacMeDan/Locolization
|
/Localiziation/main.swift
|
UTF-8
| 2,798
| 3.40625
| 3
|
[
"MIT"
] |
permissive
|
//
// main.swift
// Locoliziation
//
// Created by Dan Leonard on 3/5/18.
// Copyright © 2018 MacMeDan. All rights reserved.
//
import Foundation
//SET PATHS TO YOUR PROJECT FILES
var pathToProject: String = "/Locolization/"
var sourceFilePath: String = "Localiziation/Localizable.strings"
var destinationFilePath: String = "Localiziation/temp.strings"
var resourceFilePath: String = "Localiziation/Resources.swift"
func getValue() {
let value = needCustomKey[0]
print("""
Please enter unique key for entry:
\(value)
""", terminator: "")
let newKey = readLine()!
locolizeNewString(value, newKey: newKey)
needCustomKey.removeFirst()
getValue()
}
func error() -> String {
print("""
No `:` found please try again
""", terminator: "")
return readLine()!
}
func containsColin(_ string: String) -> Bool {
return string.contains(":")
}
// MARK: Setup
//print("""
// Please enter the path to your project.
// """, terminator: "")
//pathToProject = readLine()!
//
//print("""
// Please enter the path from your project base directory to your destination file.
// """, terminator: "")
//sourceFilePath = readLine()!
//
//print("""
// Please enter the path from your project base directory to your to your Resource file.
// """, terminator: "")
//resourceFilePath = readLine()!
// MARK: Options
print("""
Please select an option:
1) Add new entry with auto gernerated key
2) Add new entry with specified key
3) Generate Resources
4) Generate Strings
5) Generate Strings Sorted by Value not Key
6) Find Strings in file
""", terminator: "")
let answer = readLine()!
if answer == "1" {
print("""
Please enter the string you would like to locolize:
""", terminator: "")
let newString = readLine()!
print("using Key: \(newString.camelCased)")
locolizeNewString(newString)
}
if answer == "2" {
print("""
Please enter the Key : Value you would like to add:
""", terminator: "")
let newString = readLine()!
if containsColin(newString){
let componets = newString.components(separatedBy: ":")
guard componets.count == 2 else {
fatalError("Should only be 1 colin in input.")
}
let newKey = componets.first
let newValue = componets.last!
locolizeNewString(newValue, newKey: newKey)
}
}
if answer == "3" {
generateResourceEnum()
}
if answer == "4" {
generateNewStringsFile()
}
if answer == "5" {
generateNewStringsSortedByKeyFile()
}
if answer == "6" {
print("""
What is the full path to the file you would like to convert
""", terminator: "")
let filePath = readLine()!
findUnlocalisedStringsAndConvertThem(fromFilePath: filePath)
}
| true
|
23250b204720d755f0c6e7424e3f9470782ed511
|
Swift
|
boetaylor/huff
|
/huff/model/Location.swift
|
UTF-8
| 484
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
//
// Location.swift
// huff
//
// Created by Xing Hui Lu on 11/22/16.
// Copyright © 2016 Xing Hui Lu. All rights reserved.
//
import Foundation
import CoreLocation
class Location {
let longitude: CLLocationDegrees
let latitude: CLLocationDegrees
let timestamp: TimeInterval
init(location: CLLocationCoordinate2D) {
timestamp = NSDate().timeIntervalSince1970
latitude = location.latitude
longitude = location.longitude
}
}
| true
|
f34f4b000814c09a24ca08a6d5c553e606c7e418
|
Swift
|
Djaflienda/TU_iOS_Flickr
|
/TU_iOS_Flickr/View/cellPrototypes/CellSmall.swift
|
UTF-8
| 1,125
| 2.828125
| 3
|
[] |
no_license
|
//
// cellSmall.swift
// TU_iOS_Flickr
//
// Created by Djaflienda on 23/10/2018.
// Copyright © 2018 Igor Tumanov. All rights reserved.
//
import UIKit
class CellSmall: UITableViewCell {
@IBOutlet weak var smallImage: UIImageView!
@IBOutlet weak var cameraName: UILabel!
func fillCellWithData(from element: CameraModel) {
cameraName.text = element.name
if let umageURL = element.smallImageURL {
smallImage.cacheImage(url: URL(string: umageURL)!)
} else {
smallImage.image = UIImage(named: "noImage")
}
/*
THIS BLOCK OF CODE LOADS AND THEN SETS IMAGE TO UIIMAGEVIEW
BUT BECAUSE OF IMAGES HAVE TO BE LOADED EVERY TIME MY TABLEVIEW SHOWS REUSABLE CELL
IT BECOMES A CAUSE OF FREEZING WHILE SCROLLING
if let url = URL(string: element.smallImageURL) {
if let data = try? Data(contentsOf: url) {
smallImage.image = UIImage(data: data)
}
} else {
smallImage.image = UIImage(named: "noImage")
}
*/
}
}
| true
|
92984b993a8b7a09f00d492b73089fde698f828d
|
Swift
|
AntonBal/Starter
|
/Platform/Network/Protocol/NetworkPlugin.swift
|
UTF-8
| 1,682
| 2.921875
| 3
|
[] |
no_license
|
//
// NetworkPlugin.swift
// Template
//
// Created by Anton Bal’ on 11/6/19.
// Copyright © 2019 Anton Bal'. All rights reserved.
//
import Foundation
/**
- Note: Similar to Moya framework
*/
protocol NetworkPlugin {
/// Called to modify a request before sending.
func prepare(_ request: URLRequest, target: RequestConvertible) throws -> URLRequest
/// Called immediately before a request is sent over the network (or stubbed).
func willSend(_ request: Network.Request, target: RequestConvertible)
/// Called after a response has been received
func didReceive(_ result: Network.ResponseResult, target: RequestConvertible)
/// Called to modify a result before completion, but before the Network has invoked its completion handler.
func process(_ result: Network.ResponseResult, target: RequestConvertible) -> Network.ResponseResult
/// Should retry case for a request
func should(retry target: RequestConvertible, dueTo error: Error,
completion: @escaping (Network.RetryResult) -> Void)
}
extension NetworkPlugin {
func prepare(_ request: URLRequest, target: RequestConvertible) -> URLRequest { request }
func willSend(_ request: Network.Request, target: RequestConvertible) { }
func didReceive(_ result: Network.ResponseResult, target: RequestConvertible) { }
func process(_ result: Network.ResponseResult,
target: RequestConvertible) -> Network.ResponseResult { result }
func should(retry target: RequestConvertible, dueTo error: Error,
completion: @escaping (Network.RetryResult) -> Void) {
completion(.doNotRetry)
}
}
| true
|
e747d3342672baec5501e11c96f11d52aeb82f1b
|
Swift
|
JobsonMateusAlves/Agenda-iOS
|
/Agenda-iOS/Login/Service/AutenticacaoService.swift
|
UTF-8
| 3,119
| 2.53125
| 3
|
[] |
no_license
|
//
// AutenticacaoService.swift
// Agenda-iOS
//
// Created by administrador on 19/07/19.
// Copyright © 2019 administrador. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireObjectMapper
protocol AutenticacaoServiceDelegate {
func success()
func failure(error: String)
}
class AutenticacaoService {
var delegate: AutenticacaoServiceDelegate!
init(delegate: AutenticacaoServiceDelegate) {
self.delegate = delegate
}
func postCadastro(email: String, senha: String, confirmacaoSenha: String) {
AutenticacaoRequestFactory.postCadastro(email: email, senha: senha, confirmacaoSenha: confirmacaoSenha).validate().responseObject(keyPath: "data", completionHandler: { (response: DataResponse<Usuario>) in
switch response.result {
case .success:
if let usuario = response.result.value {
if let client = response.response?.allHeaderFields["Client"] as? String,
let token = response.response?.allHeaderFields["Access-Token"] as? String,
let uid = response.response?.allHeaderFields["Uid"] as? String {
usuario.token = token
usuario.client = client
usuario.uid = uid
UsuarioViewModel.save(object: usuario)
SessionControl.setHeaders()
}
}
self.delegate.success()
case .failure(let error):
self.delegate.failure(error: error.localizedDescription)
}
})
}
func postLogin(email: String, senha: String) {
AutenticacaoRequestFactory.postLogin(email: email, senha: senha).validate().responseObject(keyPath: "data", completionHandler: { (response: DataResponse<Usuario>) in
switch response.result {
case .success:
if let usuario = response.result.value {
if let client = response.response?.allHeaderFields["Client"] as? String,
let token = response.response?.allHeaderFields["Access-Token"] as? String,
let uid = response.response?.allHeaderFields["Uid"] as? String {
usuario.token = token
usuario.client = client
usuario.uid = uid
UsuarioViewModel.save(object: usuario)
SessionControl.setHeaders()
}
}
self.delegate.success()
case .failure(let error):
self.delegate.failure(error: error.localizedDescription)
}
})
}
}
| true
|
15945735103b7d5db9c4cfdfb6c2758adf07f067
|
Swift
|
fisher999/BinaryProtocol
|
/BinaryProtocol/Sources/Message/MessageBuilder/MessageBuilderContext.swift
|
UTF-8
| 604
| 2.734375
| 3
|
[] |
no_license
|
//
// MessageBuilderContext.swift
// BinaryProtocol
//
// Created by Victor on 28/07/2019.
// Copyright © 2019 Victor. All rights reserved.
//
import Foundation
public class MessageBuilderContext {
internal var message: MessageProtocol
internal init(message: MessageProtocol) {
self.message = message
}
func addSyncWord(syncWord: UInt16) -> MessageBuilderContext {
message.syncWord = syncWord
return self
}
func addPayload(payload: Payloadable) -> MessageBuilderContext {
message.payload = payload
return self
}
}
| true
|
da403a4d94456da2e8569a93602a981b599e273e
|
Swift
|
youhsuan/Fishackathon
|
/Fishackathon/Fishackathon/FirebaseManager.swift
|
UTF-8
| 1,416
| 2.796875
| 3
|
[] |
no_license
|
//
// FirebaseManager.swift
// Fishackathon
//
// Created by Susu Liang on 2018/2/3.
// Copyright © 2018年 Susu Liang. All rights reserved.
//
import Foundation
import Firebase
enum FirebaseError: Error {
case cantGetData
case cantPostData
}
class FirebaseManager {
static let shared = FirebaseManager()
func getFishesCorrespondName(fishCommonName: String, completion: @escaping (String?, Error?) -> Void) {
Database.database().reference().child("nameCorrespond").observe(.value) { (snapshot: DataSnapshot) in
if let objects = snapshot.value as? [String: String] {
let fishScientificName = objects[fishCommonName]
completion(fishScientificName, nil)
}
}
completion(nil, FirebaseError.cantGetData)
}
func getAllFishesCommonNames(completion: @escaping ([String]?, Error?) -> Void) {
Database.database().reference().child("nameCorrespond").observe(.value) { (snapshot: DataSnapshot) in
var fishCommonNames: [String] = []
if let objects = snapshot.value as? [String: String] {
for fishCommonName in objects.keys {
fishCommonNames.append(fishCommonName)
}
}
completion(fishCommonNames, nil)
}
completion(nil, FirebaseError.cantGetData)
}
}
| true
|
16602db67754f2e472228097afb948ff864c4b75
|
Swift
|
informramiz/swift-practice
|
/json.playground/Contents.swift
|
UTF-8
| 2,493
| 2.9375
| 3
|
[
"Apache-2.0"
] |
permissive
|
import Foundation
var json = """
{
"food_name": "Lemon",
"taste": "sour",
"number of calories": 17
}
""".data(using: .utf8)!
struct Food: Codable {
let foodName: String
let taste: String
let numberOfCalories: Int
enum CodingKeys: String, CodingKey {
case foodName = "food_name"
case taste = "taste"
case numberOfCalories = "number of calories"
}
}
let jsonDecoder = JSONDecoder()
do {
let food = try jsonDecoder.decode(Food.self, from: json)
print(food)
} catch {
print(error)
}
/*----------Arrays--------------*/
var jsonArrayStr = """
[
{
"title": "Groundhog Day",
"released": 1993,
"starring": ["Bill Murray", "Andie MacDowell", "Chris Elliot"]
},
{
"title": "Home Alone",
"released": 1990,
"starring": ["Macaulay Culkin", "Joe Pesci", "Daniel Stern", "John Heard", "Catherine O'Hara"]
}
]
""".data(using: .utf8)!
struct Movie: Codable {
let title: String
let released: Int
let starring: [String]
}
do {
let movies = try jsonDecoder.decode([Movie].self, from: jsonArrayStr)
print(movies)
} catch {
print(error)
}
/*----------Nested Objects--------------*/
var jsonNested = """
{
"name": "Neha",
"studentId": 326156,
"academics": {
"field": "iOS",
"grade": "A"
}
}
""".data(using: .utf8)!
struct Student: Codable {
let name: String
let studentId: Int
let academics: Academics
}
struct Academics: Codable {
let field: String
let grade: String
}
do {
let nestedObjects = try jsonDecoder.decode(Student.self, from: jsonNested)
print(nestedObjects)
} catch {
print(error)
}
//Flicker API for photos
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let flickerPhotos = """
"photos":{
"page":1,
"pages":1,
"perpage":250,
"total":"36",
"photo":[
{
"id":"47964765217",
"owner":"54915149@N06",
"secret":"d06af9f186",
"server":"65535",
"farm":66,
"title":"Boerhavia elegans",
"ispublic":1,
"isfriend":0,
"isfamily":0,
"url_m":"https://live.staticflickr.com/65535/47964765217_d06af9f186.jpg",
"height_m":"333",
"width_m":"500"
},
{
"id":"47964764862",
"owner":"54915149@N06",
"secret":"aeef31765d",
"server":"65535",
"farm":66,
"title":"Boerhavia elegans",
"ispublic":1,
"isfriend":0,
"isfamily":0,
"url_m":"https://live.staticflickr.com/65535/47964764862_aeef31765d.jpg",
"height_m":"333",
"width_m":"500"
}
]
}
}
""".data(using: .utf8)
struct FlickerPhotos {
}
| true
|
5fd2f078432f77553c20c479bbc2487ff7e50767
|
Swift
|
AdrianaPineda/training
|
/leetcode/2-medium/arrays-strings/group-anagrams-v2.swift
|
UTF-8
| 2,633
| 4.125
| 4
|
[] |
no_license
|
// https://leetcode.com/problems/group-anagrams/
/**
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase,
typically using all the original letters exactly once.
*/
// Option 2:
// loop array, generate unique key => hash table
// [key: [str1, str2, ..]
// Time complexity: O((n^2)*k)
// Space complexity: O(k*n)
func groupAnagrams(_ strs: [String]) -> [[String]] {
let sortedKeys = getSortedKeys(strs) // O((n^2)*k)
return Array(sortedKeys.values) // O(k*n)
}
func getSortedKeys(_ strs: [String]) -> [String: [String]] {
var sortedKeys = [String: [String]]()
for str in strs {
let uniqueKey = str.uniqueKey() // O(k)
guard var strsValue = sortedKeys[uniqueKey] else {
sortedKeys[uniqueKey] = [str]
continue
}
strsValue.append(str) // O(k - 2*k - 3*k - n*k) = O((n^2)*k)
sortedKeys[uniqueKey] = strsValue
}
return sortedKeys
}
extension String {
func uniqueKey() -> String {
var uniqueKeyArray = Array(repeating: 0, count: 26)
let charArray = Array(self)
let firstChar = Int(Character("a").asciiValue ?? 0)
for char in charArray {
let charIndex = Int(char.asciiValue ?? 0) - firstChar
uniqueKeyArray[charIndex] = uniqueKeyArray[charIndex] + 1
}
return uniqueKeyArray.map{String($0)}.joined(separator: "-")
}
}
// Option 1:
// loop array, sort each string => hash table
// [sorted_key: [str1, str2, ..]
// Time complexity: O(n*k(log(k) + n))
// Space complexity: O(k*n)
func groupAnagrams(_ strs: [String]) -> [[String]] {
let sortedKeys = getSortedKeys(strs) // O(k*log(k)*n) + O((n^2)*k) = O(n*k(log(k) + n))
return Array(sortedKeys.values) // O(k*n)
}
func getSortedKeys(_ strs: [String]) -> [[Character]: [String]] {
var sortedKeys = [[Character]: [String]]()
for str in strs {
let sortedString = str.sorted() // O(k*log(k))
guard var strsValue = sortedKeys[sortedString] else {
sortedKeys[sortedString] = [str]
continue
}
strsValue.append(str) // O(k - 2*k - 3*k - n*k) = O((n^2)*k)
sortedKeys[sortedString] = strsValue
}
return sortedKeys
}
print(groupAnagrams(["bdddddddddd","bbbbbbbbbbc"])) // [["bbbbbbbbbbc"],["bdddddddddd"]]
print(groupAnagrams(["eat","tea","tan","ate","nat","bat"])) // [["bat"],["nat","tan"],["ate","eat","tea"]]
print(groupAnagrams([""])) // [[""]]
print(groupAnagrams(["a"])) // [["a"]]
| true
|
cf78dd93f94bc728eb5a30d81d44f6856b44f45c
|
Swift
|
wybosys/n2
|
/src.swift/ui/N2View.swift
|
UTF-8
| 1,056
| 2.59375
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
protocol IView
{
func onlayout(rect:CGRect)
}
extension UIView
{
func rectForLayout() -> CGRect
{
return self.bounds
}
final
func __swcb_layoutsubviews()
{
var rc = self.rectForLayout()
if self.respondsToSelector(Selector("onlayout:")) {
let sf:AnyObject = self
sf.onlayout(rc)
}
}
}
class View : UIView, ObjectExt, IView
{
convenience init()
{
self.init(frame: CGRect.zeroRect)
self.oninit()
}
deinit
{
self.onfin()
}
func oninit()
{
}
func onfin()
{
}
// 边缘的留空
var paddingEdge: CGPadding = CGPadding.zeroPadding
// 内容的偏移
var offsetEdge: CGPoint = CGPoint.zeroPoint
override func rectForLayout() -> CGRect
{
var ret = self.bounds
ret.apply(self.paddingEdge)
ret.offset(self.offsetEdge)
return ret
}
func onlayout(rect: CGRect)
{
}
}
| true
|
9942bd05a8bce63e3008bbe6a51ac9e723a42347
|
Swift
|
guptasudha952/WhereIam_Swift
|
/WhereIam_Swift/ViewController.swift
|
UTF-8
| 2,260
| 2.703125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// WhereIam_Swift
//
// Created by Student 06 on 29/11/18.
// Copyright © 2018 Student 06. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController,CLLocationManagerDelegate,MKMapViewDelegate {
let locationManger = CLLocationManager()
@IBAction func clear(_ sender: UIButton) {
}
@IBOutlet weak var mapKit: MKMapView!
@IBAction func btn1(_ sender: UIButton) {
startDetectingLocation()
}
func startDetectingLocation(){
locationManger.desiredAccuracy = kCLLocationAccuracyBest
locationManger.requestWhenInUseAuthorization()
locationManger.delegate = self
locationManger.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let latitude:CGFloat,longitude:CGFloat
let currentLocation = locations.last!
latitude = CGFloat (currentLocation.coordinate.latitude)
longitude = CGFloat (currentLocation.coordinate.longitude)
print("latitude=\(latitude) and longitude=\(longitude)")
//for span and region
let span = MKCoordinateSpan.init(latitudeDelta: 0.01, longitudeDelta: 0.01)
let region = MKCoordinateRegion(center: currentLocation.coordinate, span: span)
//view on map
mapKit.setRegion(region,animated: true)
//set point on location
let anotation = MKPointAnnotation()
anotation.coordinate = currentLocation.coordinate
mapKit.addAnnotation(anotation)
let geo = CLGeocoder()
geo.reverseGeocodeLocation(currentLocation) { (placeMark, error) in
if placeMark?.count != nil
{
let placeMark = placeMark?.first!
anotation.title = placeMark?.name
}
}
}
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.
}
}
| true
|
f9b616954d297c3684e574482cea6de216aee707
|
Swift
|
vantien2905/Bizkasa
|
/Bizkasa/Modules/RateSettingManagement/Detail/Cell/HourRateSettingCell.swift
|
UTF-8
| 1,091
| 2.59375
| 3
|
[] |
no_license
|
//
// HourRateSettingCell.swift
// Bizkasa
//
// Created by Tien Dinh on 10/11/20.
// Copyright © 2020 DINH VAN TIEN. All rights reserved.
//
import UIKit
enum PriceHourSetting: String {
case onehour = "Giờ đầu:"
case twoHour = "Giờ thứ:"
case overHour = "Quá thời gian trên tính 1 ngày"
}
class HourRateSettingCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var contentLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setData(detail: CheckoutEntity?, row: Int) {
guard let detail = detail else { return }
contentLabel.text = detail.Value*.formattedWithSeparator
if row == 0 {
titleLabel.text = PriceHourSetting.onehour.rawValue
} else {
titleLabel.text = "Giờ thứ \(row + 1):"
}
}
}
| true
|
c8a3ff935d903ed161f7176231c03296a4093a80
|
Swift
|
Eleanoor/Apple-Pie
|
/Apple Pie/Apple Pie/ViewController.swift
|
UTF-8
| 2,966
| 3.34375
| 3
|
[] |
no_license
|
// Minor Programming, App Studio
//
// ViewController.swift
// Apple Pie
//
// Created by Eleanoor Polder (10979301) on 08-04-18.
// Copyright © 2018 Eleanoor Polder. All rights reserved.
//
// Create an app which is a simple word-guessing game.
import UIKit
class ViewController: UIViewController {
// Initialize variables
var listOfWords = ["apple", "pie", "hello", "world", "bug", "program", "food", "xcode", "game"]
let incorrectMovesAllowed = 7
var totalWins = 0 {
didSet {
newRound()
}
}
var totalLosses = 0 {
didSet {
newRound()
}
}
var currentGame: Game!
// Create outles for tree image, labels and letter buttons.
@IBOutlet weak var treeImageView: UIImageView!
@IBOutlet weak var correctWordLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet var letterButtons: [UIButton]!
// Function viewDidLoad.
override func viewDidLoad() {
super.viewDidLoad()
newRound()
}
// Create a function for a new round.
func newRound() {
if !listOfWords.isEmpty {
let newWord = listOfWords.removeFirst()
currentGame = Game(word: newWord, incorrectMovesRemaining: incorrectMovesAllowed, guessedLetters: [])
enableLetterButtons(true)
updateUI()
} else {
enableLetterButtons(false)
}
}
// Function for interface updates.
func updateUI() {
var letters = [String]()
for letter in currentGame.formattedWord.characters {
letters.append(String(letter))
}
let wordWithSpacing = letters.joined(separator: " ")
correctWordLabel.text = wordWithSpacing
scoreLabel.text = "Wins: \(totalWins), Losses: \(totalLosses)"
treeImageView.image = UIImage(named: "Tree \(currentGame.incorrectMovesRemaining)")
}
// Function for when a letter is pressed.
@IBAction func buttonPressed(_ sender: UIButton) {
sender.isEnabled = false
let letterString = sender.title(for: .normal)!
let letter = Character(letterString.lowercased())
currentGame.playerGuessed(letter:letter)
updateGameState()
}
// Function that keeps count of losses and wins.
func updateGameState() {
if currentGame.incorrectMovesRemaining == 0 {
totalLosses += 1
} else if currentGame.word == currentGame.formattedWord {
totalWins += 1
} else {
updateUI()
}
}
// Function for enabling letter button if pressed.
func enableLetterButtons(_ enable: Bool) {
for button in letterButtons {
button.isEnabled = enable
}
}
// Function receive memory warning.
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
c6260d815e6d12b5c764096b6d57c7b20f7e057f
|
Swift
|
Rahul1703/AIRHolland
|
/Air Holland/Utility/ActivityIndicator.swift
|
UTF-8
| 1,701
| 2.8125
| 3
|
[] |
no_license
|
//
// ActivityIndicator.swift
// Air Holland
//
// Created by Rahul on 29/09/19.
// Copyright © 2019 Rahul. All rights reserved.
//
import UIKit
import Foundation
import NVActivityIndicatorView
typealias Completion = (() -> ())
protocol ActivityIndicator {
func showIndicator(_ message:String?, stopAfter: Double?, completion:Completion?)
func hideIndicator()
}
extension ActivityIndicator {
private func setIndicatorViewDefaults() {
NVActivityIndicatorView.DEFAULT_TYPE = .ballSpinFadeLoader
NVActivityIndicatorView.DEFAULT_COLOR = UIColor.white
NVActivityIndicatorView.DEFAULT_BLOCKER_BACKGROUND_COLOR = UIColor.darkGray.withAlphaComponent(0.7)
NVActivityIndicatorView.DEFAULT_BLOCKER_SIZE = CGSize(width: 40, height: 40)
NVActivityIndicatorView.DEFAULT_BLOCKER_MESSAGE_FONT = UIFont.boldSystemFont(ofSize: 17)
}
func showIndicator(_ message:String? = nil, stopAfter: Double? = 0, completion:Completion? = nil) {
setIndicatorViewDefaults()
let activityData = ActivityData(message: "")
NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData)
if stopAfter! > 0.0 {
DispatchQueue.main.asyncAfter(deadline: .now() + stopAfter!) {
NVActivityIndicatorPresenter.sharedInstance.stopAnimating()
// handler
if let completionHanlder = completion {
completionHanlder()
}
}
}
}
// Hide indicator
func hideIndicator() {
NVActivityIndicatorPresenter.sharedInstance.stopAnimating()
}
}
| true
|
d192676cc1b4d0e2f74b6e8d6fe49f1ba64108e4
|
Swift
|
vandanpatelgithub/Facebook_SwiftUI
|
/Facebook_SwiftUI/HomePageView.swift
|
UTF-8
| 2,224
| 3.1875
| 3
|
[] |
no_license
|
//
// ContentView.swift
// Facebook_SwiftUI
//
// Created by Vandan Patel on 2/3/21.
//
import SwiftUI
struct HomePageView: View {
let facebookBlue = UIColor(red: 23/255.0, green: 120/255.0, blue: 242/255.0, alpha: 1)
@Binding var searchText: String
let stories = ["ElonMusk", "MSDhoni", "ViratKohli", "NarendraModi", "AmitShah", "TimCook"]
let posts = [
PostModel(name: "Elon Musk", post: "I am the richest and coolest man in the world. I am CEO of Tesla and SpaceX. I am worth more than $209 Billion", imageName: "ElonMusk"),
PostModel(name: "Mahendra Singh Dhoni", post: "I was the best captain Indian Cricket Team ever had.", imageName: "MSDhoni"),
PostModel(name: "Virat Kohli", post: "I am the GOAT of cricket.", imageName: "ViratKohli")
]
var body: some View {
VStack {
HStack {
Text("facebook")
.font(.system(size: 40, weight: .bold, design: .default))
.foregroundColor(Color(facebookBlue))
Spacer()
Image(systemName: "person.circle")
.resizable()
.frame(width: 35, height: 35, alignment: .center)
.foregroundColor(Color(.secondaryLabel))
}
.padding()
TextField("Serach...", text: $searchText)
.padding()
.background(Color(.systemGray5))
.cornerRadius(10)
.padding(.horizontal, 15)
ZStack {
Color(.secondarySystemBackground)
ScrollView(.vertical) {
VStack {
StoriesView(stories: stories)
ForEach(posts, id: \.self) { post in
FacebookPost(postModel: post)
.padding()
Spacer()
}
}
}
}
Spacer()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
HomePageView(searchText: .constant(""))
}
}
| true
|
52fe705aa741d8199895fd9fa1c246436220b9a0
|
Swift
|
kaua808/DevMountain--iOS-Swift
|
/Review/Unit 2/Project/PlaylistMiniProject 2/PlaylistMiniProject/PlaylistController.swift
|
UTF-8
| 952
| 2.578125
| 3
|
[] |
no_license
|
//
// PlaylistController.swift
// PlaylistMiniProject
//
// Created by admin on 4/6/16.
// Copyright © 2016 Brock. All rights reserved.
//
import Foundation
import CoreData
class PlaylistController {
static let sharedController = PlaylistController()
var playlists: [Playlist] {
let context = Stack.sharedStack.managedObjectContext
let request = NSFetchRequest(entityName: "Playlist")
let playlists = (try? context.fetch(request)) as? [Playlist]
return playlists ?? []
}
func createPlaylist(_ name: String) {
let _ = Playlist(name: name)
saveToPersistentStore()
}
func saveToPersistentStore() {
let _ = try? Stack.sharedStack.managedObjectContext.save()
}
func deletePlaylist(_ playlist: Playlist) {
let _ = Stack.sharedStack.managedObjectContext.delete(playlist)
}
}
| true
|
4b5b6216277c9a016fd108391c61c5cd21dbdcb3
|
Swift
|
uts-ios-dev/uts-ios-2019-project3-group-141
|
/TaskApp/TaskApp/ProgressView.swift
|
UTF-8
| 3,798
| 2.828125
| 3
|
[] |
no_license
|
//
// ProgressView.swift
// TaskApp
//
// Created by jean on 26/5/2562 BE.
// Copyright © 2562 Madeleine Gillard. All rights reserved.
//
import UIKit
class ProgressView: UIView {
@IBInspectable public var trackCircleColor: UIColor = UIColor.lightGray
@IBInspectable public var startGradientColor: UIColor = UIColor.blue
@IBInspectable public var endGradientColor: UIColor = UIColor.green
@IBInspectable public var textColor: UIColor = UIColor.black
private var progressLayer: CAShapeLayer!
private var trackLayer: CAShapeLayer!
private var textLayer: CATextLayer!
private var gradientLayer: CAGradientLayer!
var progress: CGFloat = 0 {
didSet{
didProgressUpdate()
}
}
override func draw(_ rect: CGRect) {
let width = rect.width
let height = rect.height
let lineWidth = 0.1 * min(width, height)
trackLayer = createCircularPath(rect: rect, strokecolor: trackCircleColor.cgColor, fillColor: UIColor.clear.cgColor, linewidth: lineWidth)
progressLayer = createCircularPath(rect: rect, strokecolor: UIColor.blue.cgColor, fillColor: UIColor.clear.cgColor, linewidth: lineWidth)
gradientLayer = CAGradientLayer()
gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.colors = [startGradientColor.cgColor, endGradientColor.cgColor]
gradientLayer.frame = rect
gradientLayer.mask = progressLayer
textLayer = createTextLayer(rect: rect, textColor: textColor.cgColor)
layer.addSublayer(trackLayer)
layer.addSublayer(gradientLayer)
layer.addSublayer(textLayer)
}
private func createCircularPath(rect: CGRect, strokecolor: CGColor, fillColor: CGColor, linewidth: CGFloat) -> CAShapeLayer {
let width = rect.width
let height = rect.height
let center = CGPoint(x: width / 2, y: height / 2)
let radius = (min(width, height) - linewidth) / 2
let startAngle = -CGFloat.pi / 2
let endAngle = startAngle + 2 * CGFloat.pi
let circularPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = strokecolor
shapeLayer.fillColor = fillColor
shapeLayer.lineWidth = linewidth
shapeLayer.lineCap = .round
return shapeLayer
}
func createTextLayer(rect: CGRect, textColor: CGColor) -> CATextLayer{
let width = rect.width
let height = rect.height
let fontSize = min(width, height) / 4
let offset = min(width, height) * 0.1
let layer = CATextLayer()
layer.string = "\(Int(progress * 100))%"
layer.backgroundColor = UIColor.clear.cgColor
layer.foregroundColor = textColor
layer.fontSize = fontSize
layer.frame = CGRect(x: 0, y: (height - fontSize - offset) / 2, width: width, height: fontSize + offset)
layer.alignmentMode = .center
return layer
}
func didProgressUpdate(){
textLayer?.string = "\(Int(progress * 100))%"
progressLayer?.strokeEnd = progress
}
}
| true
|
c53508d0eecdd4f2a7e8bc02e5b534b226005a09
|
Swift
|
pleasesavemycat/OpenRTB
|
/Sources/OpenRTB/OpenRTB2+Geo.swift
|
UTF-8
| 4,412
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// OpenRTB2+Geo.swift
//
// Copyright (c) 2019 Kelly Dun
//
// 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
extension OpenRTB2 {
/// The following enumeration lists the options to indicate how the geographic information was determined.
/// - Note: Conforms to OpenRTB 2.5 specification 5.20
public enum LocationType: Int, Codable {
case gps = 1
case ipAddress = 2
case userProvided = 3
}
/// The following enumeration lists the services and/or vendors used for resolving IP addresses to geolocations.
/// - Note: Conforms to OpenRTB 2.5 specification 5.23
public enum IPLocationService: Int, Codable {
case ip2location = 1
case neustar = 2
case maxMind = 3
case netAcuity = 4
}
/// This object encapsulates various methods for specifying a geographic location.
/// When subordinate to a `Device` object, it indicates the location of the device which can also be interpreted as the user’s current location.
/// When subordinate to a `User` object, it indicates the location of the user’s home base (i.e., not necessarily their current location).
/// The lat/lon attributes should only be passed if they conform to the accuracy depicted in the type attribute.
/// For example, the centroid of a geographic region such as postal code should not be passed.
/// - Note: Conforms to OpenRTB 2.5 specification 3.2.19
public struct Geo: Codable {
/// Latitude from -90.0 to +90.0, where negative is south.
let lat: Float?
/// Longitude from -180.0 to +180.0, where negative is west.
let lon: Float?
/// Source of location data; recommended when passing `lat`/`lon`.
let type: OpenRTB2.LocationType?
/// Estimated location accuracy in meters; recommended when lat/lon are specified and derived from a device’s location services (i.e., type = 1).
/// Note that this is the accuracy as reported from the device. Consult OS specific documentation (e.g., Android, iOS) for exact interpretation.
let accuracy: Int?
/// Number of seconds since this geolocation fix was established. Note that devices may cache location data across multiple fetches.
/// Ideally, this value should be from the time the actual fix was taken.
let lastfix: TimeInterval?
/// Service or provider used to determine geolocation from IP address if applicable (i.e., `type` = `ipAddress`).
let ipservice: OpenRTB2.IPLocationService?
/// Country code using ISO-3166-1-alpha-3.
let country: String?
/// Region code using ISO-3166-2; 2-letter state code if USA.
let region: String?
/// Region of a country using FIPS 10-4 notation. While OpenRTB supports this attribute, it has been withdrawn by NIST in 2008.
let regionfips104: String?
/// Google metro code; similar to but not exactly Nielsen DMAs.
let metro: String?
/// City using United Nations Code for Trade & Transport Locations.
let city: String?
/// Zip or postal code.
let zip: String?
/// Local time as the number +/- of minutes from UTC.
let utcoffset: Int?
}
}
| true
|
71336ff954eeb8a72cc8df7a6950b06b9e466bc2
|
Swift
|
Appracatappra/ActionData
|
/iOS Tests/Classes/Group.swift
|
UTF-8
| 635
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// Group.swift
// iOS Tests
//
// Created by Kevin Mullins on 1/26/18.
//
import Foundation
import ActionUtilities
import ActionData
class Group: ADDataTable {
static var tableName = "Groups"
static var primaryKey = "id"
static var primaryKeyType = ADDataTableKeyType.autoUUIDString
var id = UUID().uuidString
var name = ""
var people = ADCrossReference<Person>(name: "PeopleInGroup", leftKeyName: "groupID", rightKeyName: "personID")
required init() {
}
init(name: String, people: [Person] = []) {
self.name = name
self.people.storage = people
}
}
| true
|
ec504366097ef4672f6b1a82e5cb5c0cf1e3fd55
|
Swift
|
AlphaWallet/alpha-wallet-ios
|
/modules/AlphaWalletFoundation/AlphaWalletFoundation/Initializers/SkipBackupFiles.swift
|
UTF-8
| 1,069
| 2.5625
| 3
|
[
"LicenseRef-scancode-proprietary-license",
"MIT"
] |
permissive
|
// Copyright SIX DAY LLC. All rights reserved.
import Foundation
public struct SkipBackupFiles: Initializer {
private var urls: [URL] {
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true).compactMap { URL(fileURLWithPath: $0) }
paths.append(legacyFileBasedKeystore.keystoreDirectory)
return paths
}
private let legacyFileBasedKeystore: LegacyFileBasedKeystore
public init(legacyFileBasedKeystore: LegacyFileBasedKeystore) {
self.legacyFileBasedKeystore = legacyFileBasedKeystore
}
public func perform() {
urls.forEach { addSkipBackupAttributeToItemAtURL($0) }
}
@discardableResult func addSkipBackupAttributeToItemAtURL(_ url: URL) -> Bool {
let url = NSURL.fileURL(withPath: url.path) as NSURL
do {
try url.setResourceValue(true, forKey: .isExcludedFromBackupKey)
try url.setResourceValue(false, forKey: .isUbiquitousItemKey)
return true
} catch {
return false
}
}
}
| true
|
7208b9957381c7694f31f0ede6bd88cb2753411e
|
Swift
|
weiranx/Triton-Go-iOS
|
/Triton Go/View Controllers/AskPhoneNumViewController.swift
|
UTF-8
| 1,478
| 2.9375
| 3
|
[] |
no_license
|
//
// AskPhoneNumViewController.swift
// Triton Go
//
// Created by Weiran Xiong on 10/13/18.
// Copyright © 2018 Weiran Xiong. All rights reserved.
//
import UIKit
import PhoneNumberFormatter
class AskPhoneNumViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var promptLabel: UILabel!
@IBOutlet weak var phoneNumInput: UITextField!
let appDelegate = UIApplication.shared.delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
phoneNumInput.delegate = self
let firstName = appDelegate.googlUser?.profile.givenName ?? "New User"
promptLabel.text = "Hey, \(firstName). We need some more infomation about you"
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if (textField.text?.range(of: "\\(?([0-9]{3})\\)?([ .-]?)([0-9]{3})\\2([0-9]{4})", options: .regularExpression, range: nil, locale: nil) == nil) {
// wrong phone number
let alert = UIAlertController(title: "Invalid Phone Number", message: "Please enter a valid phone number", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(alertAction)
present(alert, animated: true, completion: nil)
return true
}
let formatter = PhoneNumberFormatter()
let formattedNum = formatter.string(for: textField.text ?? "")
print("\(formattedNum)")
return true
}
}
| true
|
288d7025401ddc68ef6d6c73eba1f23539cce175
|
Swift
|
MirzaGe/ListApi
|
/ListApi/dataListEntry.swift
|
UTF-8
| 521
| 2.5625
| 3
|
[] |
no_license
|
//
// dataListEntry.swift
// ListApi
//
// Created by sherry on 26/08/2021.
//
import Foundation
//{
// "userId": 1,
// "id": 9,
// "title": "nesciunt iure omnis dolorem tempora et accusantium",
// "body": "consectetur animi nesciunt iure dolore\nenim quia ad\nveniam autem ut quam aut nobis\net est aut quod aut provident voluptas autem voluptas"
// },
struct DataListEntry: Decodable, Identifiable {
var userId : Int
var id: Int
var title: String
var body: String
}
| true
|
3693a01ca383cfaea72a489a746412475f251c3a
|
Swift
|
AndyCuiYTT/YTTCoder
|
/YTTCoder/Coder/YTTJson.swift
|
UTF-8
| 4,750
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
//
// YTTJson.swift
// YTTJsonCodable
//
// Created by AndyCui on 2017/12/25.
// Copyright © 2017年 AndyCuiYTT. All rights reserved.
//
import UIKit
public protocol YTTJson: Codable {
}
public extension YTTJson {
public static func deserializeFrom(json: String, keyPath: String? = nil) throws -> Self {
var lastJSONStr = json
if let path = keyPath {
do {
if let object = try json.ytt.toDictionary(keyType: String.self, valueType: Any.self).ytt.getValue(withKeyPath: path) {
if let dic = object as? [String: Any] {
lastJSONStr = try dic.ytt.toJson()
}else if let _ = object as? [Any] {
throw YTTJsonCodableError.DecoderError
}else if let str = object as? String {
lastJSONStr = str
}else {
lastJSONStr = ""
}
}
} catch {
throw error
}
}
if let jsonData = lastJSONStr.data(using: .utf8) {
do {
let obj = try YTTJsonCoder<Self>.jsonToObject(jsonData: jsonData)
return obj
} catch {
throw error
}
}else {
throw YTTJsonCodableError.DataError
}
}
public static func deserializeFrom(dictionary: Dictionary<String, Any>, keyPath: String? = nil) throws -> Self {
do {
var jsonData: Data
if let path = keyPath {
if let dic = dictionary.ytt.getValue(withKeyPath: path) as? [String: Any] {
jsonData = try dic.ytt.toData()
}else {
throw YTTJsonCodableError.DataError
}
}else {
jsonData = try dictionary.ytt.toData()
}
let obj = try YTTJsonCoder<Self>.jsonToObject(jsonData: jsonData)
return obj
} catch {
throw error
}
}
public func toJson() throws -> String {
do {
let jsonData = try YTTJsonCoder<Self>.objectToJson(object: self)
if let jsonStr = String(data: jsonData, encoding: .utf8) {
return jsonStr
}else{
throw YTTJsonCodableError.DataError
}
} catch {
throw error
}
}
}
public extension Array where Element: YTTJson {
public static func deserializeFrom(json: String, keyPath: String? = nil) throws -> Array {
var jsonData: Data
do {
if let path = keyPath {
if let object = try json.ytt.toDictionary(keyType: String.self, valueType: Any.self).ytt.getValue(withKeyPath: path) {
if let arr = object as? [Any] {
jsonData = try arr.ytt.toData()
}else {
throw YTTJsonCodableError.DecoderError
}
}else {
throw YTTJsonCodableError.DataError
}
}else {
jsonData = try json.ytt.toData()
}
let obj = try JSONDecoder().decode(self, from: jsonData)
return obj
} catch {
throw error
}
}
public static func deserializeFrom(array: [Any])throws -> Array {
do {
let jsonData = try array.ytt.toData()
let obj = try JSONDecoder().decode(self, from: jsonData)
return obj
} catch {
throw error
}
}
}
fileprivate class YTTJsonCoder<T: YTTJson> {
/// 将 JSON 字符串转换为对象
///
/// - Parameters:
/// - jsonStr: json 字符串
/// - Returns: 转换后的对象
/// - Throws: 异常(YTTJsonCodableError)
fileprivate class func jsonToObject(jsonData: Data) throws -> T {
do {
let object = try JSONDecoder().decode(T.self, from: jsonData)
return object
} catch {
throw YTTJsonCodableError.DecoderError
}
}
/// 将对象转换为 JSON 字符串
///
/// - Parameter object: 要转换的对象
/// - Returns: 转换后的字符串
/// - Throws: 异常(YTTJsonCodableError)
fileprivate class func objectToJson(object: T) throws -> Data {
do {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
return try encoder.encode(object)
} catch {
throw YTTJsonCodableError.EncodableError
}
}
}
| true
|
2a8f552ea2dee17bb2c61709e8aa39cdc66c4c25
|
Swift
|
ideiadoluiz/silicon_valley
|
/siliconvalley/siliconvalley/Models/Image.swift
|
UTF-8
| 547
| 3
| 3
|
[] |
no_license
|
//
// Image.swift
// siliconvalley
//
// Created by Luiz Peres on 2021-10-25.
//
internal class Image: Parseable {
private(set) var medium: String?
private(set) var original: String?
init(medium: String?, original: String?) {
self.medium = medium
self.original = original
}
static func parse(dict: [String : AnyObject]?) -> Parseable {
let medium = dict?["medium"] as? String
let original = dict?["original"] as? String
return Image(medium: medium, original: original)
}
}
| true
|
4f610f475931b25245478f03e03a75184f0aebb6
|
Swift
|
alan-f10res/church
|
/churchApp/View/Leader Tools/AttendanceView.swift
|
UTF-8
| 4,778
| 2.625
| 3
|
[] |
no_license
|
//Created for churchApp (30.10.2020 )
import SwiftUI
struct AttendanceView: View {
@State var searchText: String = ""
@State var isError = false
@State var errorString = ""
@State var memberList: [MembersDemoList] = demoMembersEditList
@State var submitBtnText = "Submit"
var body: some View {
let binding = Binding<String>(get: { self.searchText },
set: { self.searchText = $0
// do whatever you want here
//filterResult(by: $0)
print($0)
})
let rowEdges = EdgeInsets(top: 18, leading: 24, bottom: 18, trailing: 24)
VStack(alignment: .leading) {
AppText(text: "Attendance", weight: .semiBold, size: 24).padding(.top, 40)
AppText(text: "Week of October 28, 2020", weight: .regular, size: 14, colorName: "Grey 3")
/// Search box
HStack {
ZStack {
RoundedRectangle(cornerRadius: 16).frame(height: 48).foregroundColor(Color("Grey 6"))
TextField("Add a note...", text: binding).padding([.leading, .trailing], 16)
}
}
ZStack(alignment: .bottom) {
List {
Section(footer: Color.clear.frame(height: 64)) {
ForEach(memberList.indices) { member in
AttendanceViewRow(data: self.$memberList[member], action: { updateSubmit() }).listRowInsets(rowEdges)
}
}
}
.padding([.leading, .trailing], -24)
.listSeparatorStyle()
AppButton(type: .findDinnerParty, shadowsRadius: 0, title: submitBtnText, LRpaddings: 0) {
print("Submit tapped")
}
.disabled(submitCount() == 0)
.opacity(submitCount() == 0 ? 0.8 : 1)
}
Spacer()
}
.padding([.leading, .trailing], 24)
.alert(isPresented: $isError) { () -> Alert in
Alert(title: Text(""), message: Text(errorString), dismissButton: .default(Text("Ok")) {
self.isError = false
self.errorString = ""
} )
}
.onAppear() { updateList() }
}
func submitCount() -> Int {
return memberList.filter {$0.approved != $0.declined}.count
}
func updateSubmit() {
let count = submitCount()
if count > 0 {
submitBtnText = "Submit \(count)"
} else {
submitBtnText = "Submit"
}
}
func updateList() {
self.memberList = demoMembersEditList
//demoMembersEditList.forEach({ self.memberList.append($0)})
}
}
struct AttendanceView_Previews: PreviewProvider {
static var previews: some View {
AttendanceView()
}
}
struct AttendanceViewRow: View {
@Binding var data: MembersDemoList
let action: () -> Void
var body: some View {
HStack(alignment: .top, spacing: 16) {
VStack {
AvatarView(image: data.avatar,size: 40)
}
VStack(alignment: .leading) {
AppText(text: data.name, weight: .semiBold, size: 18)
.lineLimit(1)
HStack(alignment: .center, spacing: 16) {
AppText(text: data.role, weight: .regular, size: 14, colorName: "Grey 3")
}
}
Spacer()
VStack(alignment: .leading) {
HStack(spacing: 8) {
Image(data.declined ? "decline-active-icon" : "decline-icon").frame(width: 32, height: 32, alignment: .center).onTapGesture(count: 1, perform: {
data.declined.toggle()
if !data.declined && !data.approved {data.declined = true; data.approved = true}
action()
})
Image(data.approved ? "approve-active-icon" : "approve-icon").frame(width: 32, height: 32, alignment: .center).onTapGesture(count: 1, perform: {
data.approved.toggle()
if !data.declined && !data.approved {data.declined = true; data.approved = true}
action()
})
}
}
}
}
}
| true
|
8a6929ad49c1233c4e69e46b64eb5898a292fda2
|
Swift
|
yenz0r/bonup-mobile
|
/bonup-mobile/bonup-mobile/Modules/ApplicationContentSection/Organizations/CompanyActionsList/Subviews/CompanyActionsListCell.swift
|
UTF-8
| 3,572
| 2.734375
| 3
|
[] |
no_license
|
//
// CompanyActionsListCell.swift
// bonup-mobile
//
// Created by Yahor Bychkouski on 16.05.21.
// Copyright © 2021 Bonup. All rights reserved.
//
import UIKit
final class CompanyActionsListCell: UITableViewCell {
enum LabelType {
case title, description, dateInfo
}
// MARK: - Static
static let reuseId = NSStringFromClass(CompanyActionsListCell.self)
// MARK: - UI variables
private var container: UIView!
private var titleLabel: BULabel!
private var descriptionLabel: BULabel!
private var dateLabel: BULabel!
// MARK: - Init
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setupSubviews()
self.setupAppearance()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Public
func setup(title: String,
descriptionInfo: String,
dateInfo: String,
dateInfoColor: UIColor) {
self.titleLabel.text = title
self.descriptionLabel.text = descriptionInfo
self.dateLabel.text = dateInfo
self.dateLabel.textColor = dateInfoColor
}
// MARK: - Setup
private func setupSubviews() {
self.container = UIView()
self.titleLabel = self.configureLabel(of: .title)
self.descriptionLabel = self.configureLabel(of: .description)
self.dateLabel = self.configureLabel(of: .dateInfo)
self.contentView.addSubview(self.container)
self.container.snp.makeConstraints { make in
make.edges.equalToSuperview().inset(10)
}
self.container.addSubview(self.titleLabel)
self.container.addSubview(self.descriptionLabel)
self.container.addSubview(self.dateLabel)
self.titleLabel.snp.makeConstraints { make in
make.leading.trailing.top.equalToSuperview().inset(10)
}
self.descriptionLabel.snp.makeConstraints { make in
make.leading.trailing.equalTo(self.titleLabel)
make.top.equalTo(self.titleLabel.snp.bottom).offset(10)
}
self.dateLabel.snp.makeConstraints { make in
make.trailing.leading.equalTo(self.descriptionLabel)
make.bottom.equalToSuperview().offset(-10)
make.top.equalTo(self.descriptionLabel.snp.bottom).offset(10)
}
}
private func setupAppearance() {
self.container.setupSectionStyle()
self.selectionStyle = .none
self.backgroundColor = .clear
}
// MARK: - Configure
private func configureLabel(of type: LabelType) -> BULabel {
let label = BULabel()
label.numberOfLines = 0
switch type {
case .title:
label.font = .avenirHeavy(20)
label.theme_textColor = Colors.defaultTextColor
label.textAlignment = .left
case .description:
label.font = .avenirRoman(16)
label.theme_textColor = Colors.defaultTextColorWithAlpha
label.textAlignment = .left
case .dateInfo:
label.font = .avenirHeavy(13)
label.textAlignment = .right
}
return label
}
}
| true
|
fc3a8aa321db250857a772b44c9c4d1a40a2084d
|
Swift
|
zorro27/funny
|
/intensive/intensive/PlayerViewController.swift
|
UTF-8
| 3,360
| 2.578125
| 3
|
[] |
no_license
|
//
// PlayerViewController.swift
// intensive
//
// Created by Роман Зобнин on 09.03.2021.
//
import UIKit
class PlayerViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
@IBOutlet weak var reloadButton: UIButton!
@IBOutlet weak var errorLabel: UILabel!
// var players: [Player] = [Player(
// name: "LeBron",
// lastName: "James",
// team: lakers,
// position: "SF",
// height: "6'8"),
// Player(name: "Anthony",
// lastName: "Davis",
// team: lakers,
// position: "PF",
// height: "7'0"),
// Player(name: "Jimmy",
// lastName: "Butler",
// team: heat,
// position: "SG",
// height: "6'6")]
var players:[Player] = []
let apiClient: ApiClient = ApiClientImpl()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Players"
navigationController?.navigationBar.prefersLargeTitles = true
reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return players.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let player = players[indexPath.row]
cell.textLabel?.text = player.fullName
cell.detailTextLabel?.text = player.team.fullName
return cell
}
func reloadData() {
activityIndicatorView.startAnimating()
errorLabel.isHidden = true
reloadButton.isHidden = true
apiClient.getPlayers(completion: {result in
DispatchQueue.main.async {
self.activityIndicatorView.stopAnimating()
switch result {
case .success(let players):
self.players = players
case .failure(_):
self.players = []
self.errorLabel.isHidden = false
self.reloadButton.isHidden = false
}
self.tableView.reloadData()
}
})
}
@IBAction func reloadButtonTuch(_ sender: Any) {
reloadData()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: .main)
let viewController = storyboard.instantiateViewController(identifier: "playersDetailsViewController") as! playersDetailsViewController
viewController.player = players[indexPath.row]
navigationController?.pushViewController(viewController, animated: true)
tableView.deselectRow(at: indexPath, animated: true)
}
}
| true
|
b893b2955de4194ee86ee48442962d9271936768
|
Swift
|
nikans/Analytical
|
/Analytical/Classes/Core/Analytical.swift
|
UTF-8
| 4,212
| 2.84375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// Analytical
// Analytical
//
// Created by Dal Rupnik on 18/07/16.
// Copyright © 2016 Unified Sense. All rights reserved.
//
import Foundation
public typealias Properties = [String : Any]
public typealias EventName = String
public enum Property : String {
case category = "category"
case time = "time"
public enum Launch : String {
case application = "application"
case options = "launchOptions"
}
public enum Purchase : String {
case affiliation = "affiliation"
case country = "country"
case currency = "currency"
case item = "item"
case price = "price"
case sku = "sku"
case shipping = "shipping"
case quantity = "quantity"
case tax = "tax"
case transactionId = "transactionId"
}
public enum User : String {
case age = "age"
case gender = "gender"
}
}
/*!
Some providers may not support logging certain events separately. Analytical still logs those events,
using Analytical methods, but default event names are used instead and are tracked as normal events.
- Purchase: Log a purchase
- ScreenView: Log a screen view
*/
public enum DefaultEvent : String {
case purchase = "AnalyticalEventPurchase"
case screenView = "AnalyticalEventScreenView"
}
public protocol Analytical {
//
// MARK: Common Methods
//
/*!
Prepares analytical provider with selected properities and initializes all systems.
- parameter properties: properties of analytics.
*/
func setup(with properties: Properties?)
/*!
Called when app is activated.
*/
func activate()
/*!
Manually force the current loaded events to be dispatched.
*/
func flush()
/*!
Resets all user data.
*/
func reset()
//
// MARK: Tracking
//
/*!
Logs a specific event to analytics.
- parameter name: name of the event
- parameter properties: additional properties
*/
func event(name: EventName, properties: Properties?)
/*!
Logs a specific screen to analytics.
- parameter name: name of the screen
- parameter properties: additional properties
*/
func screen(name: EventName, properties: Properties?)
/*!
Track time for event name
- parameter name: name of the event
- parameter properties: properties
*/
func time (name: EventName, properties: Properties?)
/*!
Finish tracking time for event
- parameter name: event
- parameter properties: properties
*/
func finish (name: EventName, properties: Properties?)
//
// MARK: User Tracking
//
/*!
Identify an user with analytics. Do this as soon as user is known.
- parameter userId: user id
- parameter properties: different traits and properties
*/
func identify(userId: String, properties: Properties?)
/*!
Connect the existing anonymous user with the alias (for example, after user signs up),
and he was using the app anonymously before. This is used to connect the registered user
to the dynamically generated ID it was given before. Identify will be called automatically.
- parameter userId: user
*/
func alias(userId: String, forId: String)
/*!
Sets properties to currently identified user.
- parameter properties: properties
*/
func set(properties: Properties)
/*!
Increments currently set property by a number.
- parameter property: property to increment
- parameter number: number to incrememt by
*/
func increment(property: String, by number: NSDecimalNumber)
/*!
Make a purchase for the current user.
- parameter amount: amount
- parameter properties: properties, such as SKU, Product ID, Tax, etc.
*/
func purchase(amount: NSDecimalNumber, properties: Properties?)
}
| true
|
4c7742adf0e0cdf9ba3e35869734865f7723048f
|
Swift
|
godsavemenow/bus-time2.0
|
/busy/ViewController.swift
|
UTF-8
| 2,612
| 2.953125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// busy
//
// Created by Lucas Vinícius José da Silva on 13/03/20.
// Copyright © 2020 Lucas Vinícius José da Silva. All rights reserved.
//
import UIKit
import Foundation
class ViewController: UIViewController {
@IBOutlet var listaHorarios: UILabel!
@IBOutlet var cronometroLabel: UILabel!
@IBOutlet var firstView: UIView!
@IBOutlet var horarioInput: UITextField!
@IBOutlet weak var warning: UILabel!
var timer = Timer()
var count:Int=0
var acumuladorStr:String = ""
var horariosString:[String] = []
@IBAction func confirmarButton(_ sender: Any) {
horarios.removeFirst();
iniciarCronometro(index: 0)
}
var horarios:[Int] = []
@IBAction func addHorario(_ sender: Any) {
if(horarios.count<5){
let horatext = horarioInput.text
acumuladorStr = acumuladorStr + (horatext ?? " ") + "\n"
print(acumuladorStr)
listaHorarios.text = acumuladorStr
let auxHora = horatext?.components(separatedBy: ":")
let hora = auxHora?[0] ?? "0"
let minuto = auxHora?[1] ?? "0"
let intHora = Int(hora) ?? 0
let intMinuto = Int(minuto) ?? 0
horarios.append(intHora*60 + intMinuto)
horarioInput.text = ""
}else{
horarioInput.text = ""
warning.isHidden = false
}
}
@IBAction func iniciarTimer(_ sender: Any) {
firstView.isHidden = true;
iniciarCronometro(index: 0);
}
func iniciarCronometro(index:Int){
let date = Date()
let calender = Calendar.current
let components = calender.dateComponents([.hour,.minute], from: date)
let hour = components.hour
let minute = components.minute
count = horarios[index] - (hour ?? 1)*60 - (minute ?? 0)
count = count * 60
scheduledTimerWithTimeInterval()
}
func scheduledTimerWithTimeInterval(){
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
@objc func updateTime() {
if(count >= 0){
var minutes = String(count / 60)
var seconds = String(count % 60)
if(minutes.count<2){
minutes = "0"+minutes
}
if(seconds.count<2){
seconds = "0"+seconds
}
cronometroLabel.text = minutes + ":" + seconds
count-=1
}
}
override func viewDidLoad() {
super.viewDidLoad()
warning.isHidden = true
}
}
| true
|
65555cbc678a1ea522589cfd6152926b24e82d91
|
Swift
|
briankeane/swiftOAuthExamples
|
/SwiftOauthExample/GenericOAuthHandlerProtocol.swift
|
UTF-8
| 1,619
| 2.578125
| 3
|
[] |
no_license
|
//
// GenericOAuthHandlerProtocol.swift
// playolaIphone
//
// Created by Brian D Keane on 12/7/17.
// Copyright © 2017 Brian D Keane. All rights reserved.
//
import Foundation
import OAuthSwift
import PromiseKit
import SafariServices
protocol GenericOAuthHandlerProtocol: SFSafariViewControllerDelegate
{
// MARK: required
var oauthSwift: OAuth2Swift? { get set }
/// the UserDefaults key for retrieving the stored accessToken
var accessTokenKey:String! { get set }
/// the UserDefaults key for retrieving the stored refreshToken. This is an
/// optional because the refreshToken may not exist
var refreshTokenKey:String? { get set }
func generateOAuth() -> OAuth2Swift
/// if successful, resolves to a promise containing the accessTokenString and
/// refreshTokenString if it exists
func authorize() -> Promise<(String, String?)>
// MARK: default implementations provided in extension
var defaults:UserDefaults { get }
var signInStatusChanged:Notification.Name { get set }
func checkForStoredTokens()
/// if successful, resolves to a promise containing the accessTokenString
/// and the refreshTokenString if it exists
func signIn(presentingViewController:UIViewController) -> Promise<(String, String?)>
func signOut()
func isSignedIn() -> Bool
func accessToken() -> String?
func refreshToken() -> String?
func clearTokens()
func storeTokens(accessTokenString:String, refreshTokenString:String?)
}
extension GenericOAuthHandlerProtocol
{
}
| true
|
484f009b410d79ab9f10ef79b1d90ced37debb4e
|
Swift
|
Eiphoria6237/RecipeListApp
|
/RecipeList_1/Views/RecipeListView.swift
|
UTF-8
| 1,827
| 3.046875
| 3
|
[] |
no_license
|
//
// ContentView.swift
// RecipeList_1
//
// Created by LIU SHURUI on 2021/03/15.
//
import SwiftUI
struct RecipeListView: View {
@EnvironmentObject var model:RecipeModel
var body: some View {
NavigationView {
VStack(alignment:.leading) {
Text("All Recipes")
.bold()
.padding(.top, 40)
.font(.largeTitle)
ScrollView {
LazyVStack(alignment:.leading) {
ForEach(model.recipes) { r in
NavigationLink (destination:RecipeDetailView(recipe:r), label:{
HStack(spacing:20) {
Image(r.image).resizable().scaledToFill().frame(width:50,height:50,alignment:.center).clipped()
VStack(alignment:.leading) {
Text(r.name)
.foregroundColor(.black)
.bold()
RecipeHighlights(highlights: r.highlights)
.foregroundColor(.black)
}
}
})
}
}
}
}
.navigationBarHidden(true)
.padding(.leading)
}
}
}
struct RecipeListView_Previews: PreviewProvider {
static var previews: some View {
RecipeListView()
.environmentObject(RecipeModel())
}
}
| true
|
f4db3e6d4ecb4f471a8eb87c43df026b929203b4
|
Swift
|
yangyansong-adbe/aepsdk-edge-ios
|
/Sources/EdgeNetworkHandlers/EdgeEndpoint.swift
|
UTF-8
| 1,851
| 2.703125
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// Copyright 2021 Adobe. All rights reserved.
// This file is licensed to you 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 REPRESENTATIONS
// OF ANY KIND, either express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
import Foundation
/// Represents all the known endpoints for the Edge Network
enum EdgeEndpoint: String {
/// The production Edge Network endpoint
case production = "prod"
/// The pre-production Edge Network endpoint
case preProduction = "pre-prod"
/// The integration Edge Network endpoint
case integration = "int"
/// Initializes the appropriate `EdgeEndpoint` enum for the given `optionalRawValue`
/// - Parameter optionalRawValue: a `RawValue` representation of a `EdgeEndpoint` enum, default is `production`
init(optionalRawValue: RawValue?) {
guard let rawValue = optionalRawValue,
let validEndpoint = EdgeEndpoint(rawValue: rawValue) else {
self = EdgeConstants.Defaults.ENDPOINT
return
}
self = validEndpoint
}
/// Computes the endpoint URL based on this
var endpointUrl: String {
switch self {
case .production:
return EdgeConstants.NetworkKeys.EDGE_ENDPOINT
case .preProduction:
return EdgeConstants.NetworkKeys.EDGE_ENDPOINT_PRE_PRODUCTION
case .integration:
return EdgeConstants.NetworkKeys.EDGE_ENDPOINT_INTEGRATION
}
}
}
| true
|
2b299062ba5cb19b9e08dad3f8d1b482a5346b79
|
Swift
|
vikramraj87/YCC-Manager
|
/YCC Manager/Playgrounds/Filterable.playground/Contents.swift
|
UTF-8
| 1,105
| 3.515625
| 4
|
[] |
no_license
|
import Cocoa
struct Person {
var name: String
var mobileNumber: Int
}
protocol FilterableTableContent {
var primaryField: String { get }
var secondaryField: String { get }
}
extension Person: FilterableTableContent {
var primaryField: String {
return name
}
var secondaryField: String {
return String(mobileNumber)
}
}
let persons: [FilterableTableContent] = [
Person(name: "Vikram Raj Gopinathan", mobileNumber: 9958235698),
Person(name: "Kirthika Vikram", mobileNumber: 9871318150),
Person(name: "Nirmal Raj Gopinathan", mobileNumber: 1234567890),
Person(name: "Kalpana Nirmal", mobileNumber: 2345678901),
Person(name: "Naishadha Nirmal", mobileNumber: 3456789012),
Person(name: "Makshidha Nirmal", mobileNumber: 4567890123)
]
let str = "98"
let items = persons.filter { item in
if item.primaryField.lowercased().contains(str.lowercased()) {
return true
}
return item.secondaryField.lowercased().contains(str.lowercased())
}
items
let text = "Vikram Raj" as NSString
let ran = text.range(of: "ra")
ran
let ranb = text.range(of: "bz")
ranb.lowerBound == NSNotFound
| true
|
6b92e7d2b9cd96b9b6c5252dd9ca1e114645f2c2
|
Swift
|
sergeiKalinin35/ToDoList
|
/ToDoList/Models/Task.swift
|
UTF-8
| 568
| 2.625
| 3
|
[] |
no_license
|
//
// Task.swift
// ToDoList
//
// Created by Sergey on 28.08.2021.
//
import RealmSwift
// модель данных связана с Realm данные на прямую не меняются //только в приложении Realm
class Task: Object {
@objc dynamic var name = ""
@objc dynamic var note = ""
@objc dynamic var date = Date()
@objc dynamic var isComplete = false
}
class TaskList: Object {
@objc dynamic var name = ""
@objc dynamic var date = Date()
let tasks = List<Task>()
}
| true
|
6a4a7e7119dbb6128fa32aa8de2421c77d049302
|
Swift
|
SaurontheMighty/Iphone-App
|
/IphoneApp/FirebaseTest/View Controllers/SignUpViewController.swift
|
UTF-8
| 4,004
| 2.75
| 3
|
[] |
no_license
|
//
// SignUpViewController.swift
// FirebaseTest
//
// Created by Joseph on 11/09/19.
// Copyright © 2019 AAS. All rights reserved.
//
import UIKit
import Firebase
import FirebaseFirestore
class SignUpViewController: UIViewController {
@IBOutlet weak var firstnameText: UITextField!
@IBOutlet weak var lastnameText: UITextField!
@IBOutlet weak var emailtext: UITextField!
@IBOutlet weak var passwordText: UITextField!
@IBOutlet weak var signupButton: UIButton!
@IBOutlet weak var errorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setUpElements()
}
func setUpElements(){
errorLabel.alpha=0
Utilities.styleFilledButton(signupButton)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
func ValidateFields() -> String? {
//check for filled in fields
if firstnameText.text?.trimmingCharacters(in: .whitespacesAndNewlines)==""{
return "Please Fill in Fields"
}
if lastnameText.text?.trimmingCharacters(in: .whitespacesAndNewlines)==""{
return "Please Fill in Fields"
}
if emailtext.text?.trimmingCharacters(in: .whitespacesAndNewlines)==""{
return "Please Fill in Fields"
}
if passwordText.text?.trimmingCharacters(in: .whitespacesAndNewlines)==""{
return "Please Fill in Fields"
}
//check password
let cleanedPassword=passwordText.text!.trimmingCharacters(in: .whitespacesAndNewlines)
if Utilities.isPasswordValid(cleanedPassword)==false{
return "Your password isn't secure,it should have 8 characters, a special charcter and a number!"
}
return nil
}
func showError(_ message:String){
errorLabel.text=message
errorLabel.alpha=1
}
func transitionToHome() {
let homeViewController = storyboard?.instantiateViewController(withIdentifier: Constants.Storyboard.homeViewController) as? HomeViewController
view.window?.rootViewController = homeViewController
view.window?.makeKeyAndVisible()
}
@IBAction func signupTapped(_ sender: Any) {
//Validate
let error=ValidateFields()
if error != nil{
showError(error!)
}
else{
//Create
// Create cleaned versions of the data
let firstName = firstnameText.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let lastName = lastnameText.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let email = emailtext.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let password = passwordText.text!.trimmingCharacters(in: .whitespacesAndNewlines)
Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
if err != nil{
self.showError("Error! Cannot create user")
}
else{
let db = Firestore.firestore()
db.collection("users").addDocument(data: ["firstname":firstName, "lastname":lastName, "uid": result!.user.uid ]) { (error) in
if error != nil {
// Show error message
self.showError("Error saving user data")
}
}
// Transition to the home screen
self.transitionToHome()
}
}
//Transition
}
}
}
| true
|
ea21d73601171c600850882b51bc94d450589d0c
|
Swift
|
Akash2002/EcoStay
|
/EcoStayiOS/EcoTourism/Code/Utility Classes/DateUtility.swift
|
UTF-8
| 3,047
| 3.1875
| 3
|
[] |
no_license
|
//
// DateUtility.swift
// EcoTourism
//
// Created by Akash Veerappan on 2/11/19.
// Copyright © 2019 Akash Veerappan. All rights reserved.
//
import Foundation
class DateUtility {
static func getCurrentDate () -> String {
let date = Date()
var cal: Calendar = Calendar.current
let hour = cal.component(.hour, from: date)
let minute = cal.component(.minute, from: date)
let year = cal.component(.year, from: date)
let month = cal.component(.month, from: date)
let day = cal.component(.day, from: date)
return String(month) + "-" + String(day) + "-" + String(year)
}
static func getDateDate(date: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
if let d: Date = dateFormatter.date(from: date) {
return d
} else {
return Date()
}
}
static func getDateString(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
if var d: String = dateFormatter.string(from: date) {
return d
} else {
return "Error Decoding Date"
}
}
static func getDuration (date1: Date, date2: Date) -> Int {
let form = DateComponentsFormatter()
form.maximumUnitCount = 2
form.unitsStyle = .full
form.allowedUnits = [.year, .month, .day]
var s = form.string(from: date1, to: date2)!
print ("Duration: " + s)
var dIndex = s.index(of: " ")
s = s.substring(to: dIndex!)
return Int(s)!
}
static func getDateRange (from: Date, to: Date) -> [Date] {
var dates = [Date]()
var fromDate = from
while fromDate <= to {
dates.append(fromDate)
fromDate = Calendar.current.date(byAdding: .day, value: 1, to: fromDate)!
}
return dates
}
static func isDateInRange (date1: Date, date2: Date, compareDate: Date) -> Bool {
if (compareDate <= date2) && (compareDate >= date1) {
return true
} else {
return false
}
}
static func isDateGreater (placeHolderDate: Date, dateToBeCompared: Date) -> Bool {
if (dateToBeCompared > placeHolderDate) {
return true
} else {
return false
}
}
static func addDaysToDate (date: Date, numDaysToBeAdded: Int) -> String {
var cal: Calendar = Calendar.current
var newDate = cal.date(byAdding: Calendar.Component.day, value: numDaysToBeAdded, to: date)!
var tyear = cal.component(Calendar.Component.year, from: newDate)
var tmonth = cal.component(Calendar.Component.month, from: newDate)
var tday = cal.component(Calendar.Component.day, from: newDate)
var completeDateString2 = String(tmonth) + "-" + String(tday) + "-" + String(tyear);
return completeDateString2
}
}
| true
|
0605c4e6a40863243c6c9ebd57cf9b967fea6887
|
Swift
|
aliazadeh/AZCalendar
|
/SwiftSample/SwiftSample/classes/Type/AZPersianMonthType.swift
|
UTF-8
| 1,127
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
//
// PersianMonthType.swift
// SwiftSample
//
// Created by Ali on 10/6/17.
// Copyright © 2017 Ali Azadeh. All rights reserved.
//
import Foundation
public enum AZPersianMonthType : Int {
case farvardin = 1
case ordibehesht = 2
case khordad = 3
case tir = 4
case mordad = 5
case shahrivar = 6
case mehr = 7
case aban = 8
case azar = 9
case dey = 10
case bahman = 11
case esfand = 12
var description: String {
switch self {
case .farvardin:
return "farvardin"
case .ordibehesht:
return "ordibehesht"
case .khordad:
return "khordad"
case .tir:
return "tir"
case .mordad:
return "mordad"
case .shahrivar:
return "shahrivar"
case .mehr:
return "mehr"
case .aban:
return "aban"
case .azar:
return "azar"
case .dey:
return "dey"
case .bahman:
return "bahman"
case .esfand:
return "esfand"
}
}
}
| true
|
6686559c87a58a68cf66f6f01316db59c0775316
|
Swift
|
indiamela/LikeHere
|
/LikeHere/Helpers/RefleshControll.swift
|
UTF-8
| 1,252
| 2.9375
| 3
|
[] |
no_license
|
//
// RefleshControll.swift
// LikeHere
//
// Created by Taishi Kusunose on 2021/07/12.
//
import Foundation
import SwiftUI
struct RefreshControl: View {
@State private var isRefreshing = false
var coordinateSpaceName: String
var onRefresh: () -> Void
var body: some View {
GeometryReader { geometry in
if geometry.frame(in: .named(coordinateSpaceName)).midY > 50 {
Spacer()
.onAppear() {
print("refleshing = true")
isRefreshing = true
}
} else if geometry.frame(in: .named(coordinateSpaceName)).maxY < 10 {
Spacer()
.onAppear() {
if isRefreshing {
isRefreshing = false
print("refleshing = false")
onRefresh()
}
}
}
HStack {
Spacer()
if isRefreshing {
ProgressView()
} else {
Text("離して更新")
}
Spacer()
}
}.padding(.top, -50)
}
}
| true
|
a5c80374d9f2598ed2d546f608bd11e5d0cc1c00
|
Swift
|
miolabs/MIOFramework
|
/MIOSwiftTranspiler/test/local/classes/willset-didset.swift
|
UTF-8
| 456
| 3.1875
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
let stepCounter = StepCounter()
stepCounter.totalSteps = 200
stepCounter.totalSteps = 360
stepCounter.totalSteps = 896
stepCounter.totalSteps = 500
| true
|
c3018321309537ee35794453b963760bbc835b68
|
Swift
|
ChrisMash/AlertPresenter
|
/TestApps/Shared/AlertType.swift
|
UTF-8
| 2,338
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
//
// AlertType.swift
// Created by Chris Mash on 05/07/2021.
//
import UIKit
@objc enum AlertType: Int, CaseIterable {
case alert
case actionSheet
#if os(iOS)
case actionSheetPositioned
#endif
case custom
#if os(iOS)
case customPositioned
#endif
func buttonTitle() -> String {
return AlertFactory.buttonTitle(forType: self)
}
func alert(index: UInt) -> UIViewController {
return AlertFactory.alert(forType: self, index: index)
}
}
@objc class AlertFactory: NSObject {
@objc static func allAlertTypes() -> [Int] {
return AlertType.allCases.map{ $0.rawValue }
}
@objc static func buttonTitle(forType type: AlertType) -> String {
switch type {
case .alert:
return "Show Alerts"
case .actionSheet:
return "Show Action Sheets"
#if os(iOS)
case .actionSheetPositioned:
return "Show Action Sheets Positioned"
#endif
case .custom:
return "Show Custom Alerts"
#if os(iOS)
case .customPositioned:
return "Show Custom Alerts Positioned"
#endif
}
}
@objc static func alert(forType type: AlertType, index: UInt) -> UIViewController {
switch type {
case .alert:
return UIAlertController.basic(title: "alert title \(index)",
message: "message \(index)",
style: .alert)
case .actionSheet:
return UIAlertController.basic(title: "sheet title \(index)",
message: "message \(index)",
style: .actionSheet)
#if os(iOS)
case .actionSheetPositioned:
return UIAlertController.basic(title: "positioned sheet title \(index)",
message: "message \(index)",
style: .actionSheet)
#endif
case .custom:
return CustomAlertController(title: "custom title \(index)")
#if os(iOS)
case .customPositioned:
return CustomAlertController(title: "positioned custom title \(index)")
#endif
}
}
}
| true
|
9caa59794426a3649b4d7415c7a0ee5a0a653200
|
Swift
|
voximplant/flutter_callkit
|
/example/ios/Runner/UserDefault.swift
|
UTF-8
| 1,329
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
/*
* Copyright (c) 2011-2021, Zingaya, Inc. All rights reserved.
*/
import Foundation
fileprivate let userDefaults = UserDefaults(suiteName: "group.com.voximplant.flutterCallkit.example")
@propertyWrapper
struct UserDefault<T: Codable> {
private let key: String
private let defaultValue: T
init(_ key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}
var wrappedValue: T {
get {
if let encodedValue = userDefaults?.object(forKey: key) as? Data,
let decodedValue = decode(encodedValue) {
return decodedValue
}
return defaultValue
}
set {
if let encodedValue = encode(newValue) {
userDefaults?.set(encodedValue, forKey: key)
}
}
}
private func encode(_ value: T) -> Data? {
try? JSONEncoder().encode(value)
}
private func decode(_ data: Data) -> T? {
try? JSONDecoder().decode(T.self, from: data)
}
}
@propertyWrapper
struct NullableUserDefault<T> {
private let key: String
init(_ key: String) {
self.key = key
}
var wrappedValue: T? {
get { userDefaults?.object(forKey: key) as? T }
set { userDefaults?.set(newValue, forKey: key) }
}
}
| true
|
75b59802554310bcfe053bd73b892f262db1802c
|
Swift
|
aoenth/Important-Coding-Practice
|
/Recursion/Factorial.playground/Contents.swift
|
UTF-8
| 218
| 3.515625
| 4
|
[] |
no_license
|
// A function "factorial" to calculate the factorial of an integer
import UIKit
func factorial(_ N: Int) -> Int {
if N > 1 {
return factorial(N - 1) * N
} else {
return 1
}
}
factorial(5)
| true
|
077084efda5f9378d96b6fb5570a414bf11af463
|
Swift
|
danielrobleM/themoviedbApiCleanSwift
|
/themoviedbapi/ShowMovie/ShowMoviePresenter.swift
|
UTF-8
| 934
| 2.859375
| 3
|
[] |
no_license
|
//
// ShowMoviePresenter.swift
// themoviedbapi
//
// Created by Daniel on 02-06-20.
// Copyright (c) 2020 idorm. All rights reserved.
//
import UIKit
protocol ShowMoviePresentationLogic {
func presentMovie(response: ShowMovie.GetMovie.Response)
func presentPoster(response: ShowMovie.GetPoster.Response)
}
class ShowMoviePresenter: ShowMoviePresentationLogic {
weak var viewController: ShowMovieDisplayLogic?
// MARK: ShowMoviePresentationLogic
func presentMovie(response: ShowMovie.GetMovie.Response) {
let viewModel = ShowMovie.GetMovie.ViewModel(
title: response.movie.title,
overview: response.movie.overview,
releaseDate: response.movie.releaseDate
)
viewController?.displayMovie(viewModel: viewModel)
}
func presentPoster(response: ShowMovie.GetPoster.Response) {
viewController?.displayPoster(viewModel: ShowMovie.GetPoster.ViewModel(UIImage: response.UIImage))
}
}
| true
|
492a110f61b37689f732fa63ab2d5ca63a5fc254
|
Swift
|
liamdkane/AC3.2Unit2FinalAssessment
|
/Unit2FinalAssessment/Unit2FinalAssessment/Unit2FinalTableViewController.swift
|
UTF-8
| 2,970
| 2.546875
| 3
|
[] |
no_license
|
//
// Unit2FinalTableViewController.swift
// Unit2FinalAssessment
//
// Created by C4Q on 10/6/16.
// Copyright © 2016 C4Q. All rights reserved.
//
import UIKit
class Unit2FinalTableViewController: UITableViewController {
var crayons = [Crayon]()
//delegate method!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "CRAYONS YO!"
for c in crayolaColors {
if let crayon = Crayon(fromRuthBaderGinsburg: c) {
crayons.append(crayon)
}
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
// MARK: - Table view data source
//delegate methods
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return crayons.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Color Cell", for: indexPath)
let currentColour = crayons[indexPath.row]
let backgroundColor = UIColor(red: CGFloat(currentColour.red), green: CGFloat(currentColour.green), blue: CGFloat(currentColour.blue), alpha: 1.0)
cell.backgroundColor = backgroundColor
if currentColour.blue < 0.25 && currentColour.green < 0.25 && currentColour.red < 0.25 {
cell.textLabel?.textColor = .white
}
cell.textLabel?.text = currentColour.name
//cell.set = currentColour.name
// Configure the cell...
return cell
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
//target-action method
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let tappedCell = sender as? UITableViewCell {
if segue.identifier == "detailSegueID" {
let dVC = segue.destination as? DetailViewController
dVC?.view.backgroundColor = tappedCell.backgroundColor
dVC?.label.textColor = tappedCell.textLabel?.textColor
dVC?.label.text = tappedCell.textLabel?.text
}
}
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
}
| true
|
9d96008d7a55d9e57a2e97ac8bd112e1e141db78
|
Swift
|
yupliang/MianShiTi
|
/2叉树/BSTTree.swift
|
UTF-8
| 3,976
| 3.140625
| 3
|
[] |
no_license
|
//
// BSTTree.swift
// MianshiTi
//
// Created by Qiqiuzhe on 2019/6/28.
// Copyright © 2019 QiQiuZhe. All rights reserved.
//
import Foundation
class BSTTree<Key:Comparable, Value> {
var size = 0
var root: BSTNode<Key, Value>?
public func add(key:Key, value:Value) {
root = add(node: root, key: key, value: value)
}
public func containes(key:Key) -> Bool {
if getNode(node: root,key: key) != nil {
return true
}
return false
}
public func getSize() -> Int {
return size
}
public func remove(key:Key) -> Value? {
if let dNode = getNode(node: root, key: key) {
root = remove(node: root, key: key)
return dNode.value
}
return nil
}
public func levelTree(node: BSTNode<Key, Value>?) -> String? {
if let node = node {
var r = ""
let queue = Queue()
queue.enqueue(node)
var i = 0
while queue.isEmpty() == false {
let n:BSTNode<Key,Value> = queue.dequeue() as! BSTNode<Key, Value>
if i==0 {
r = "\(n.key!)"
} else {
r = "\(r)->\(n.key!)"
}
if let l = n.left {
queue.enqueue(l)
}
if let r = n.right {
queue.enqueue(r)
}
i += 1
}
return r
}
return nil
}
private func remove(node: BSTNode<Key,Value>?, key: Key) -> BSTNode<Key,Value>? {
if let node = node {
if node.key > key {
node.left = remove(node: node.left, key: key)
return node
} else if node.key < key {
node.right = remove(node: node.right, key: key)
return node
} else {
if node.left == nil {
return node.right
}
if node.right == nil {
return node.left
}
let minMaxNode = getMinValue(node: node.right)!
minMaxNode.right = removeMin(node: node.right)
minMaxNode.left = node.left
return minMaxNode
}
}
return nil
}
private func getMinValue(node:BSTNode<Key,Value>?) -> BSTNode<Key,Value>? {
if let node = node {
if let lNode = node.left {
return getMinValue(node: lNode)
}
return node
}
return nil
}
private func removeMin(node:BSTNode<Key,Value>?) -> BSTNode<Key,Value>? {
if let node = node {
if let lNode = node.left {
node.left = removeMin(node: lNode)
return node
} else {
return node.right
}
}
return nil
}
private func getNode(node: BSTNode<Key,Value>?, key:Key) -> BSTNode<Key,Value>? {
if let node = node {
if node.key == key {
return node
} else if node.key<key {
return getNode(node: node.right, key: key)
} else {
return getNode(node: node.left, key: key)
}
}
return nil
}
private func add(node:BSTNode<Key,Value>?, key:Key, value:Value) -> BSTNode<Key,Value>? {
if let node = node {
if node.key > key {
node.left = add(node: node.left, key: key, value: value)
return node
} else if node.key < key {
node.right = add(node: node.right, key: key, value: value)
return node
} else {
node.value = value
return node
}
} else {
size += 1
return BSTNode(key: key, value: value)
}
}
}
| true
|
95d9710844605460d1ce0e91f0ed0680ecc36351
|
Swift
|
sabyathak/CodeChallangeDay3
|
/Contents.swift
|
UTF-8
| 2,002
| 3.4375
| 3
|
[] |
no_license
|
import UIKit
//var scholars = [ "Chloe" : [18 : "Likes to takes Photos!"], "Maya" : [18: "Likes to contort arms"]]
//
//for pair in scholars {
// print(pair.key)
//}
var scholarNames = ["Aileen",
"Aishiki",
"Ameera",
"Cady",
"Ellen",
"Elora",
"Fiona",
"Halle",
"Hunter",
"Jamie",
"Kyla",
"Maira",
"Maya",
"Michelle",
"Nailah",
"Natalie",
"Nicoletta",
"Pegah",
"Sabyatha",
"Sophia"]
var scholarAge = [ 17, //Aileen
14, //Aishiki
14, //Ameera
13, //Cady
17, //Ellen
15, //Elora
14, //Fiona
16, //Halle
17, //Hunter
15, //Jamie
15, //Kyla
15, //Maira
15, //Maya
16, //Michelle
15, //Nailah
16, //Natalie
15, //Nicoletta
18, //Pegah
17, //Sabyatha
14 //Sophia
]
var scholarHobby = ["making Youtube videos", //Aileen
"listening to musical theather", //Aishiki
"running", //Ameera
"ballet", //Cady
"likes playing with her dogs", //Ellen
"playing the Sims", //Elora
"playing flute", //Fiona
"playing golf", //Halle
"likes dancing", //Hunter
"painting", //Jamie
"reading", //Kyla
"playing with motion graphics", //Maira
"reading", //Maya
"sleeping", //Michelle
"reading fan fiction", //Nailah
"playing soccer", //Natalie
"reading", //Nicolatta
"drawing", //Pegah
"likes crocheting", //Sabyatha
"swimming"//Sophia
]
//print(names[0],age[0],hobby[0])
for name in 0..19{
print("\(scholarNames[name]) is \(scholarAge[name]) years old and likes \
for age in 0..<scholarAge.count{
print(scholarAge[age])
}
for hobby in 0..<scholarHobby.count{
print(scholarHobby[hobby])
}
| true
|
2373bbb5acc2f03a0fead5813e28383a2d17d6ca
|
Swift
|
wwalpha/pocket-cards
|
/frontend/swift/PocketCards/Scenes/Handwriting/HandwritingInteractor.swift
|
UTF-8
| 5,577
| 2.90625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// HandwritingInteractor.swift
// PocketCards
//
// Created by macmini on 2022/10/06.
//
//
import Amplify
import Combine
import Foundation
import UIKit
import Vision
class HandwritingInteractor {
var presenter: HandwritingPresenter?
private var manager: QuestionManager = .init()
private var isCorrect = false
private var isAnswered = false
init(loadUrl: String, subject: String) {
manager.subject = subject
manager.loadUrl = loadUrl
}
}
extension HandwritingInteractor: HandwritingBusinessLogic {
func initialize() {
Task {
guard let question = await manager.next() else { return }
presenter?.showNext(q: question)
}
}
func next() {
Task {
// get next question
guard let question = await manager.next() else { return }
// show question
presenter?.showNext(q: question)
// 問題無視
isAnswered = false
}
}
func destroy() {
manager.clear()
}
func vision(image: UIImage) {
// orientation
guard let orientation = CGImagePropertyOrientation(rawValue: UInt32(image.imageOrientation.rawValue)) else { return }
// ci image
guard let ciImage = CIImage(image: image) else { return }
debugPrint(image, ciImage, orientation)
// Create a new image-request handler.
let handler = VNImageRequestHandler(ciImage: ciImage, orientation: orientation)
// Create a new request to recognize text.
let request = VNRecognizeTextRequest { request, _ in
guard let observations = request.results as? [VNRecognizedTextObservation] else {
print("The observations are of an unexpected type.")
return
}
// 解析結果の文字列を連結する
let maximumCandidates = 1
var recognizedText = ""
for observation in observations {
guard let candidate = observation.topCandidates(maximumCandidates).first else { continue }
recognizedText += candidate.string
}
print(1234, recognizedText)
}
// language
request.recognitionLanguages = ["ja-JP"]
request.recognitionLevel = .accurate
do {
// Perform the text-recognition request.
try handler.perform([request])
} catch {
print("Unable to perform the requests: \(error).")
}
}
func confirmAnswer(image: UIImage) {
presenter?.showLoading()
// vision(image: image)
// convert image to jpeg
guard let jpegImage = image.jpegData(compressionQuality: 1) else { return }
// create file uuid
let imageKey = UUID().uuidString + ".jpeg"
print(Date())
// upload data to s3
Amplify.Storage.uploadData(key: imageKey, data: jpegImage) {
result in
switch result {
case let .success(uploadedData):
print(uploadedData)
Task {
do {
// check answer
let handwriting = try await self.checkAnswer(imageKey: imageKey)
// hide loading screen
self.presenter?.hideLoading()
Task {
// 回答済の場合、かつ再確認は正解の場合
if self.isAnswered, self.isCorrect {
try await self.updateAnswer(correct: false, result: nil)
} else {
// update answer status
try await self.updateAnswer(correct: self.isCorrect, result: handwriting)
}
}
} catch let err {
debugPrint(err)
}
}
case let .failure(error):
print(error)
}
}
}
private func updateAnswer(correct: Bool, result: String?) async throws {
// 正解の場合、次の質問の表示
if isCorrect {
Audio.playCorrect()
// 回答結果のアップデート
try await manager.onUpdate(correct: correct)
// get next question
guard let question = await manager.next() else { return }
// show question
presenter?.showNext(q: question)
// answered
isAnswered = false
} else {
Audio.playInCorrect()
// 不正解の場合、エラー表示
presenter?.showError(result: result!)
// answered
isAnswered = true
}
}
private func checkAnswer(imageKey: String) async throws -> String {
let parameters = ["key": imageKey]
// call api: image to text
let res = try await API.request(URLs.VISION_HANDWRITING, method: .post, parameters: parameters)
.validate()
.serializingDecodable(HandwritingServices.Handwriting.Response.self)
.value
var correct = false
debugPrint(res.results)
// check answer
res.results.forEach { item in
if self.manager.checkAnswer(answer: item) {
correct = true
}
}
isCorrect = correct
return res.results.joined(separator: " | ")
}
}
| true
|
fcb1fc8027c7deb62c93928dcfcec4222c64d15d
|
Swift
|
RickctvDev/My-Grandpa
|
/My Grandpa/SceneChanger.swift
|
UTF-8
| 5,459
| 2.65625
| 3
|
[] |
no_license
|
//
// SceneChanger.swift
// My Grandpa
//
// Created by Rick Crane on 25/11/2017.
// Copyright © 2017 Rick Crane. All rights reserved.
//
import Foundation
import SpriteKit
class SceneChanger : SpriteCreator {
private let _scene : SKScene!
private let _texture : String!
private let _zPosition : CGFloat!
private let _anchorPoint : CGPoint!
private let _name : String?
private let audio = AudioMaker()
private let arrowXScale : CGFloat = 0.10
private let arrowOffset : CGFloat = 4
override init(scene: SKScene, texture: String, zPosition: CGFloat, anchorPoints: CGPoint?, name : String?) {
_scene = scene
_texture = texture
_zPosition = 4
_anchorPoint = anchorPoints
_name = name
super.init(scene: _scene, texture: "arrowLeft", zPosition: _zPosition, anchorPoints: _anchorPoint, name : _name)
self.xScale = arrowXScale
self.yScale = self.xScale
self.zPosition = zPosition
self.name = sceneChangeArrowLeftName
self.position = CGPoint(x: scene.frame.minX + self.frame.size.width - arrowOffset, y: scene.frame.midY)
let rightArrow = SpriteCreator(scene: scene, texture: "arrow", zPosition: self.zPosition, anchorPoints: nil, name: sceneChangeArrowRightName)
rightArrow.scale(to: self.size)
rightArrow.position = CGPoint(x: scene.frame.maxX - rightArrow.frame.size.width + arrowOffset, y: scene.frame.midY)
scene.addChild(rightArrow)
if scene.name == layoutOfHouseArray.first{
self.isHidden = true
}else if scene.name == layoutOfHouseArray.last{
rightArrow.isHidden = true
}
_scene.childNode(withName: sceneChangeArrowRightName)?.alpha = 0
self.alpha = 0
}
func enableTouchEventsOnArrowControls(){
let waitAction = SKAction.wait(forDuration: 1)
_scene.run(waitAction) {
self._scene.childNode(withName: sceneChangeArrowRightName)?.run(SKAction.fadeIn(withDuration: 0.2))
self.run(SKAction.fadeIn(withDuration: 0.2))
}
}
func rightArrowTapped(moveWithDuration : Double){
movedFromAnotherScene = true
movedToSceneFromLeftArrowTouched = false
audio.playButtonClickSound(scene: _scene, atVolume: defaultSoundVolume)
_scene.childNode(withName: sceneChangeArrowRightName)?.removeFromParent()
_scene.childNode(withName: sceneChangeArrowLeftName)?.removeFromParent()
let duration : Double = moveWithDuration
let wait = SKAction.wait(forDuration: duration)
if let grandpa = _scene.childNode(withName: grandpaName) as? Grandpa{
grandpa.removeAllActions()
grandpa.moveToNextRoom(goingLeft: false, duration: duration)
movingRightThroughHousePresentScene(runAction: wait)
}else{
movingRightThroughHousePresentScene(runAction: wait)
}
}
func leftArrowTapped(moveWithDuration : Double){
movedFromAnotherScene = true
movedToSceneFromLeftArrowTouched = true
audio.playButtonClickSound(scene: _scene, atVolume: defaultSoundVolume)
_scene.childNode(withName: sceneChangeArrowRightName)?.removeFromParent()
_scene.childNode(withName: sceneChangeArrowLeftName)?.removeFromParent()
let duration : Double = moveWithDuration
let wait = SKAction.wait(forDuration: duration)
if let grandpa = _scene.childNode(withName: grandpaName) as? Grandpa{
grandpa.removeAllActions()
grandpa.moveToNextRoom(goingLeft: true, duration: duration)
movingLeftThroughHousePresentScene(runAction: wait)
}else{
movingLeftThroughHousePresentScene(runAction: wait)
}
}
private func movingLeftThroughHousePresentScene(runAction : SKAction){
var sceneToGoTo : SKScene!
_scene.run(runAction) {
if self._scene.name == livingRoomName {
sceneToGoTo = BedroomScene(size: UIScreen.main.bounds.size)
}else if self._scene.name == bedroomName {
print("No Where to go to")
}else if self._scene.name == bathroomName {
sceneToGoTo = LivingRoomScene(size: UIScreen.main.bounds.size)
}
prepareForNewScene(sceneToPresent: sceneToGoTo, currentScene: self._scene, fadeWithDuration: 0.5, audioPlayer: nil)
}
}
private func movingRightThroughHousePresentScene(runAction : SKAction){
var sceneToGoTo : SKScene!
_scene.run(runAction) {
if self._scene.name == livingRoomName {
sceneToGoTo = BathroomScene(size: UIScreen.main.bounds.size)
}else if self._scene.name == bedroomName {
sceneToGoTo = LivingRoomScene(size: UIScreen.main.bounds.size)
}else if self._scene.name == bathroomName {
print("No Where to go to")
}
prepareForNewScene(sceneToPresent: sceneToGoTo, currentScene: self._scene, fadeWithDuration: 0.5, audioPlayer: nil)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
93581d74a88699c94a315324be4390c52d43c524
|
Swift
|
Anurag15990/locusideas-ios
|
/client/client/common/Models/UserModels/Designer.swift
|
UTF-8
| 4,255
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// Designer.swift
// client
//
// Created by Anurag Agnihotri on 3/20/16.
// Copyright © 2016 LocusIdeas. All rights reserved.
//
import Foundation
import ObjectMapper
/// Model for Designers
class Designer: NSObject, Mappable {
var designerDescription: Description
var links: Links
var offices: OfficeCollection
var contact: Contact
var approvalStatus: String?
var createdAt: String?
var updatedAt: String?
var createdBy: String?
var updatedBy: String?
override init() {
designerDescription = Description()
links = Links()
offices = OfficeCollection()
contact = Contact()
super.init()
}
required init?(_ map: Map) {
designerDescription = Description(map)!
links = Links(map)!
offices = OfficeCollection(map)!
contact = Contact(map)!
}
func mapping(map: Map) {
designerDescription <- map["description"]
links <- map["links"]
offices <- map["offices"]
contact <- map["contact"]
approvalStatus <- map["status"]
createdAt <- map["createdAt"]
updatedAt <- map["updatedAt"]
createdBy <- map["createdBy"]
updatedBy <- map["updatedBy"]
}
class Description: NSObject, Mappable {
var short: String?
var complete: String?
override init() {
super.init()
}
required init?(_ map: Map) {
}
func mapping(map: Map) {
short <- map["short"]
complete <- map["complete"]
}
}
/// Model for Social Links
class Links: NSObject, Mappable {
var primary: String?
var social: [LinkType]?
var articles: [LinkType]?
var others: [LinkType]?
override init() {
super.init()
}
required init?(_ map: Map) {
}
func mapping(map: Map) {
primary <- map["primary"]
social <- map["social"]
articles <- map["articles"]
others <- map["others"]
}
/// Type of Links
class LinkType: NSObject, Mappable {
var type: String?
var title: String?
var url: String?
override init() {
super.init()
}
required init?(_ map: Map) {
}
func mapping(map: Map) {
type <- map["type"]
title <- map["title"]
url <- map["url"]
}
}
}
/// Model for list of offices for a particular designer.
class OfficeCollection: NSObject, Mappable {
var headquarter: Office?
var others: [Office]?
override init() {
super.init()
}
required init?(_ map: Map) {
}
func mapping(map: Map) {
headquarter <- map["headquarter"]
others <- map["others"]
}
}
/// Model for Designer Contact
class Contact: NSObject, Mappable {
var phone: PhoneCollection?
override init() {
phone = PhoneCollection()
super.init()
}
required init?(_ map: Map) {
phone = PhoneCollection(map)!
}
func mapping(map: Map) {
phone <- map["phone"]
}
class PhoneCollection: NSObject, Mappable {
var primary: Phone?
var others: [Phone]?
override init() {
super.init()
}
required init?(_ map: Map) {
}
func mapping(map: Map) {
primary <- map["primary"]
others <- map["others"]
}
}
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.