text stringlengths 8 1.32M |
|---|
import SwiftUI
struct ContentView: View {
@State var show = false
var body: some View {
ZStack {
LottieCard(title: "스위프트UI", icon: "qrcode.viewfinder", animate: "sending-email", color1: Color(#colorLiteral(red: 0.05882352963, green: 0.180392161, blue: 0.2470588237, alpha: 1)), color2: Color(#colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)))
.offset(y: show ? 140: 20)
.animation(.spring(response: 0.6, dampingFraction: 0.6, blendDuration: 0))
.onTapGesture {
self.show.toggle()
}
LottieCard(title: "스위프트UI", icon: "qrcode.viewfinder", animate: "School", color1: Color(#colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1)), color2: Color(#colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)))
.offset(x: show ? -200: 00)
.rotationEffect(Angle(degrees: show ? 120: 0))
.animation(.spring(response: 0.6, dampingFraction: 0.6, blendDuration: 0))
.onTapGesture {
self.show.toggle()
}
LottieCard(title: "스위프트UI", icon: "qrcode.viewfinder", animate: "map", color1: Color(#colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)), color2: Color(#colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1)))
.offset(x: show ? -200: 00)
.rotationEffect(Angle(degrees: show ? 50: 0))
.animation(.spring(response: 0.6, dampingFraction: 0.6, blendDuration: 0))
.onTapGesture {
self.show.toggle()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// DatabaseError.swift
// PokeApp
//
// Created by Taufik Rohmat on 19/08/21.
// Copyright © 2019 TMLI IT DEV. All rights reserved.
//
import Foundation
enum DatabaseError: Error {
case writeError
case readError
case invalidAttributes
case attributesNotFound
case forbiddenAccess
case requestLimit
case custom(String)
var localizedDescription: String {
switch self {
case .writeError:
return "Database write error occurred"
case .readError:
return "Database read error occurred"
case .invalidAttributes:
return "Attribute was invalid"
case .attributesNotFound:
return "Attribute was not found"
case .forbiddenAccess:
return "You cannot select this stage"
case .requestLimit:
return "Request exceeded the limit"
case .custom(let error):
return error
}
}
}
extension DatabaseError: Equatable {
static func ==(lhs: DatabaseError, rhs: DatabaseError) -> Bool {
switch (lhs, rhs) {
case (.writeError, .writeError):
return true
case (.readError, .readError):
return true
case (.invalidAttributes, .invalidAttributes):
return true
case (.attributesNotFound, .attributesNotFound):
return true
case (.forbiddenAccess, .forbiddenAccess):
return true
case (.requestLimit, .requestLimit):
return true
case (let .custom(content1), let .custom(content2)):
return content1 == content2
default:
return false
}
}
}
|
//
// ContentView.swift
// RockPaperScissors
//
// Created by kit chun on 7/7/2021.
//
import SwiftUI
func getRandomMove() -> Int {
Int.random(in: 0 ..< 3)
}
struct ContentView: View {
let totalRound = 5
@State private var round = 1
@State private var opponentMove = getRandomMove()
var moves = ["Rock", "Paper", "Scissors"]
@State private var message = ""
@State private var nextRound = false
@State private var score = 0
@State private var isFinished = false
var body: some View {
VStack(spacing: 40) {
Text("Round \(round)").font(.largeTitle).fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
VStack(spacing: 20) {
ForEach(0 ..< 3) { index in
Button(action: {tappedMove(index)}, label: {
Image(moves[index]).renderingMode(.original).clipShape(Circle())
})
}
}
}.alert(isPresented: $nextRound) {
Alert(title: isFinished ? Text("Game Finished"): Text(round == totalRound ? "Final Round!":"\(totalRound - round) round(s) left..."), message: Text(message), dismissButton: isFinished ? .default(Text("play again")) {
isFinished = false
score = 0
round = 1
} : .default(Text("continue")))
}
}
func tappedMove(_ playerMove: Int) {
// 0, 1 -> -1 lose
// 0, 2 -> -2 win
// 1, 0 -> 1 win
// 1, 2 -> -1 lose
// 2, 0 -> 2 lose
// 2, 1 -> 1 win
let calculation = playerMove - opponentMove
let shouldWin = calculation == 1 || calculation == -2
let shouldLose = calculation == -1 || calculation == 2
let prefixMessage = "He picked \(moves[opponentMove])"
if shouldWin {
message = "\(prefixMessage). You win!"
score += 1
round += 1
} else if shouldLose {
message = "\(prefixMessage). You lose!"
round += 1
} else {
message = "\(prefixMessage). Draw, pick again!"
}
if round >= totalRound {
message = "\(message) Your final score is \(score) out of \(totalRound)"
isFinished = true
}
opponentMove = getRandomMove()
nextRound = true
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// TFNearbyUsersViewController.swift
// TaskForce
//
// Created by DB MAC MINI on 8/30/17.
// Copyright © 2017 Devbatch(Pvt) Ltd. All rights reserved.
//
import UIKit
//import GoogleMaps
class MapViewController: UIViewController/*, GMSMapViewDelegate*/
{
// @IBOutlet weak var mapView: GMSMapView!
@IBOutlet weak var lblAddress: UILabel!
var latitude : Double!
var longitude : Double!
var address = ""
override func viewDidLoad()
{
super.viewDidLoad()
lblAddress.text = address
if latitude != nil && longitude != nil && latitude != 0
{
// let camera = GMSCameraPosition.camera(withLatitude: latitude, longitude: longitude, zoom: 15.0)
// mapView.camera = camera
//
// mapView.isMyLocationEnabled = true
// mapView.settings.myLocationButton = true
//
// let marker = GMSMarker()
// marker.position = CLLocationCoordinate2D(latitude: CLLocationDegrees(latitude), longitude: CLLocationDegrees(longitude))
// marker.map = mapView
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(true)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
@IBAction func backBtnAction(_ sender: Any)
{
self.navigationController?.popViewController(animated: true)
}
}
|
// ParseStarterProject-Swift
//
// Created by Rohith on 05/06/17.
// Copyright © 2017 Parse. All rights reserved.
//
import UIKit
import Parse
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.enableLocalDatastore()
let parseConfiguration = ParseClientConfiguration(block: { (ParseMutableClientConfiguration) -> Void in
ParseMutableClientConfiguration.applicationId = "0c355ebe0f9abff257028fd5723653dcc0be0090"
ParseMutableClientConfiguration.clientKey = "ad7be9172724acd035c2e72ad37168d8bfdb8e28"
ParseMutableClientConfiguration.server = "http://ec2-34-209-238-84.us-west-2.compute.amazonaws.com:80/parse"
})
Parse.initialize(with: parseConfiguration)
let defaultACL = PFACL();
defaultACL.getPublicReadAccess = true
PFACL.setDefault(defaultACL, withAccessForCurrentUser: true)
if application.applicationState != UIApplicationState.background {
}
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let installation = PFInstallation.current()
installation.setDeviceTokenFrom(deviceToken)
installation.saveInBackground()
PFPush.subscribeToChannel(inBackground: "") { (succeeded, error) in // (succeeded: Bool, error: NSError?) is now (succeeded, error)
if succeeded {
print("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.\n");
} else {
print("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %@.\n", error)
}
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.\n")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %@\n", error)
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handle(userInfo)
if application.applicationState == UIApplicationState.inactive {
PFAnalytics.trackAppOpened(withRemoteNotificationPayload: userInfo)
}
}
}
|
//
// TimelineView.swift
// TweetSearchApp
//
// Created by Mitsuaki Ihara on 2020/12/03.
//
import SwiftUI
struct TimelineView: View {
var tweets: [Tweet]
@Binding var maxId: Int
var body: some View {
List(tweets) { tweet in
TweetRowView(tweet: tweet).onAppear {
if tweets.isLastItem(tweet) {
print("Last tweet appear: ", tweet.id)
self.maxId = tweet.id
}
}
}
}
}
|
//
// ViewController.swift
// MotionVisualize
//
// Created by 渡辺泰伎 on 2017/01/14.
// Copyright © 2017年 Project. All rights reserved.
//
import UIKit
class title: UIViewController {
@IBOutlet weak var webview: UIWebView!
@IBOutlet weak var logoPng: UIImageView!
@IBOutlet weak var bgPic: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
logoPng.isHidden = true
bgPic.isHidden = true
let url = Bundle.main.url(forResource: "logo", withExtension: "gif")!
let data = try! Data(contentsOf: url)
webview.load(data, mimeType: "image/gif", textEncodingName: "UTF-8", baseURL: NSURL() as URL)
Timer.scheduledTimer(timeInterval: 3.5, target: self, selector: #selector(self.onTick(_:)), userInfo: nil, repeats: false)
// 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.
}
//startボタンでgetMotion画面に遷移
@IBAction func goGetMotion(_ sender: AnyObject) {
let targetView = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "getMotion")
targetView.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
self.present(targetView, animated: true, completion: nil)
}
func onTick(_ timer: Timer){
webview.isHidden = true
logoPng.isHidden = false
bgPic.isHidden = false
}
}
|
//
// atemOSCSwiftUIApp.swift
// atemOSCSwiftUI
//
// Created by Peter Steffey on 12/24/20.
//
import SwiftUI
@main
struct atemOSCApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
|
//
// ProductController.swift
// Shake Your Moody
//
// Created by Robin PAUQUET on 10/06/2016.
// Copyright © 2016 Robin PAUQUET. All rights reserved.
//
import UIKit
class ProductController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var stack: UIStackView!
@IBOutlet weak var imgBack: UIImageView!
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var imgCoeur: UIButton!
@IBOutlet weak var lstTag: UIStackView!
@IBOutlet weak var lblAbout: UILabel!
@IBOutlet weak var tvAbout: UITextView!
@IBOutlet weak var lstTags: UIScrollView!
@IBOutlet weak var collectionView: UICollectionView!
var product:Product!
override func viewDidLoad() {
super.viewDidLoad()
product = ProductsManager.sharedInstance.getActualProduct()
imgBack.downloadedFrom(link: product.picture, contentMode: .ScaleAspectFill)
lblTitle.text = product.title
tvAbout.text = product.about
lblAbout.text = "Description"
if (NSUserDefaults.standardUserDefaults().boolForKey("product_id_" + product.id)){
imgCoeur.setBackgroundImage(UIImage(named:"coeur_plein"), forState: UIControlState.Normal)
} else {
imgCoeur.setBackgroundImage(UIImage(named:"coeur_vide"), forState: UIControlState.Normal)
}
//First get the nsObject by defining as an optional anyObject
}
@IBAction func coeurClick(sender: AnyObject) {
if (NSUserDefaults.standardUserDefaults().boolForKey("product_id_" + product.id)){
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "product_id_" + product.id)
imgCoeur.setBackgroundImage(UIImage(named:"coeur_vide"), forState: UIControlState.Normal)
} else {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "product_id_" + product.id)
imgCoeur.setBackgroundImage(UIImage(named:"coeur_plein"), forState: UIControlState.Normal)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
// MARK: - UICollectionViewDataSource protocol
// tell the collection view how many cells to make
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return ProductsManager.sharedInstance.getActualProduct().tags.count
}
// make a cell for each cell index path
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionTagsCell
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.myLabel.text = ProductsManager.sharedInstance.getActualProduct().tags[indexPath.item]
cell.backgroundColor = UIColor.darkGrayColor() // make cell more visible in our example project
cell.layer.borderColor = UIColor.grayColor().CGColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8
return cell
}
// change background color when user touches cell
func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
// let cell = collectionView.cellForItemAtIndexPath(indexPath)
// cell?.backgroundColor = UIColor.redColor()
}
// change background color back when user releases touch
func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) {
//let cell = collectionView.cellForItemAtIndexPath(indexPath)
//cell?.backgroundColor = UIColor.yellowColor()
}
// MARK: - UICollectionViewDelegate protocol
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// handle tap events
//ProductsManager.sharedInstance.setActualProduct(indexPath.item)
// print("You selected cell #\(indexPath.item)!")
}
} |
//
// Converters.swift
// TrocoSimples
//
// Created by gustavo r meyer on 7/8/17.
// Copyright © 2017 gustavo r meyer. All rights reserved.
//
import UIKit
class Convert {
/**
Serialize dictionary to Json data
@return: Data
@param: dictionary
*/
class func dictionaryToJson(_ dictionary:[String:Any]) -> Data? {
do {
return try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)
} catch {
print("dictionaryToJson error: \(error.localizedDescription) ")
}
return nil
}
/**
Remove all charset to return just number
@return: Data
@param: dictionary
*/
class func removePhoneMask(_ phone:String?) -> String? {
guard let phone = phone else {
return ""
}
var phoneNumber = phone.replacingOccurrences(of: " ", with: "")
phoneNumber = phoneNumber.replacingOccurrences(of: "(", with: "")
phoneNumber = phoneNumber.replacingOccurrences(of: ")", with: "")
phoneNumber = phoneNumber.replacingOccurrences(of: "-", with: "")
return phoneNumber
}
/**
Remove all charset to return just number
@return: Data
@param: dictionary
*/
class func removeCpfMask(_ cpf:String?) -> String {
guard let cpf = cpf else {
return ""
}
var cpfNumber = cpf.replacingOccurrences(of: ".", with: "")
cpfNumber = cpfNumber.replacingOccurrences(of: "-", with: "")
return cpfNumber
}
/**
Remove format number to string 0,00
@return: string
@param: value
*/
class func formatterMoney(value:NSNumber ) -> String {
return Convert.formatterMoney(value: value, moneySymbol: "")
}
class func justNumbers(_ string:String) -> String {
// remove from String: "$", ".", ","
var text = string
let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive)
text = regex.stringByReplacingMatches(in: text, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, string.characters.count), withTemplate: "")
return text
}
class func stringToNumber(_ string:String) -> NSNumber {
// remove from String: "$", ".", ","
var text = string
let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive)
text = regex.stringByReplacingMatches(in: text, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, string.characters.count), withTemplate: "")
let double = (text as NSString).doubleValue
let number = NSNumber(value: (double / 100))
return number
}
/**
Remove format number to string R$0,00
@return: string
@param: value
*/
class func formatterMoneyPtBy(value:NSNumber ) -> String {
return Convert.formatterMoney(value: value, moneySymbol: "R$ ")
}
/**
Remove format number to string <moneySymbol>$0,00
@return: string
@param: value
@param: money symbol
*/
class func formatterMoney(value:NSNumber, moneySymbol:String ) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "pt_BR")
formatter.currencySymbol = moneySymbol
return formatter.string(from: value) ?? "\(moneySymbol)0,00"
}
/**
Remove convert string to date
@return: Date
@param: string
@param: date Format
*/
class func stringToDate(from:String, dateFormat:String = "dd/MM/yyyy HH:mm:ss") -> Date?{
guard !from.isEmpty
else {
return nil
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = DateFormatter.Style.long
dateFormatter.dateFormat = dateFormat
dateFormatter.timeZone = TimeZone.current
// let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "pt_BR")
// dateFormatter.dateFormat = dateFormat
let myDate = dateFormatter.date(from: from)!
return myDate
}
/**
Remove convert date to string
@return: String
@param: string
@param: date Format
*/
class func dateToString(from: Date, dateFormat: String = "'MM'/'YYYY") -> String{
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "pt_BR")
dateFormatter.dateFormat = dateFormat
let somedateString = dateFormatter.string(from: from)
return somedateString
}
/**
Remove convert string R$ 0,00 to NUmeric
@return: Number
@param: text
*/
class func moneyPtBrTo(text: String) -> NSNumber {
if text.isEmpty {
return NSNumber(value: 0.0)
}
var textOnlyNumbers = text.replacingOccurrences(of: " ", with: "")
textOnlyNumbers = textOnlyNumbers.replacingOccurrences(of: ".", with: "")
textOnlyNumbers = textOnlyNumbers.replacingOccurrences(of: ",", with: ".")
textOnlyNumbers = textOnlyNumbers.replacingOccurrences(of: "R$", with: "")
return NSNumber(value: Double(textOnlyNumbers)!)
}
/**
Remove convert string with .-/ to NUmeric
@return: Number
@param: text
*/
class func cpfCnpjTo(text: String) -> NSNumber {
if text.isEmpty {
return NSNumber(value: 0.0)
}
var textOnlyNumbers = text.replacingOccurrences(of: " ", with: "")
textOnlyNumbers = textOnlyNumbers.replacingOccurrences(of: ".", with: "")
textOnlyNumbers = textOnlyNumbers.replacingOccurrences(of: "-", with: "")
textOnlyNumbers = textOnlyNumbers.replacingOccurrences(of: "/", with: "")
return NSNumber(value: Double(textOnlyNumbers)!)
}
class func cpfCnpjToString(text: String) -> String {
if text.isEmpty {
return ""
}
var textOnlyNumbers = text.replacingOccurrences(of: " ", with: "")
textOnlyNumbers = textOnlyNumbers.replacingOccurrences(of: ".", with: "")
textOnlyNumbers = textOnlyNumbers.replacingOccurrences(of: "-", with: "")
textOnlyNumbers = textOnlyNumbers.replacingOccurrences(of: "/", with: "")
return textOnlyNumbers
}
}
|
//
// Stock+CoreDataClass.swift
// Stocks
//
// Created by Данила on 30.08.2020.
// Copyright © 2020 Dobrotolyubov Danila. All rights reserved.
//
//
import Foundation
import CoreData
@objc(Stock)
public class Stock: NSManagedObject {
}
|
import Foundation
// MARK: - ℹ️ Инструкция
//
// Чтобы выполнить практическое задание, вам потребуется:
// 1. Прочитайте условие задания
// 2. Напишите ваше решение ниже в этом файле в разделе "Решение".
// 3. После того как решение будет готово, запустите Playground,
// чтобы проверить свое решение тестами
// MARK: - ℹ️ Условие задания
//
// 1. Создайте перечисление `Species`
// 2. Добавьте в него кейсы `mammal`, `bird`, `fish`
// 3. Создайте переменную `specie` типа `Species` и присвойте ей значение кейса `fish`
// 4. Создайте строковую переменную description
// 5. Используя switch проверьте кейс в переменной `specie`
// 5.1 для кейса `mammal` сохраните в переменную description строку "Млекопитающее"
// 5.2 для кейса `bird` сохраните в переменную description строку "Птица"
// 5.3 для кейса `fish` сохраните в переменную description строку "Рыба"
//
// MARK: - 🧑💻 Решение
// --- НАЧАЛО КОДА С РЕШЕНИЕМ ---
enum Species {
case mammal, bird, fish
}
var specie: Species = .fish
var description: String
switch specie {
case .mammal:
description = "Млекопетающее"
case .bird:
description = "Птица"
case .fish:
description = "Рыба"
}
// --- КОНЕЦ КОДА С РЕШЕНИЕМ ---
// MARK: - 🛠 Тесты
// - Здесь содержится код запуска тестов для вашего решения
// - ⚠️ Не меняйте этот код
TestRunner.runTests(.default(specie, description))
|
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBAction func openAction(_ sender: NSMenuItem) {
let openPanel = NSOpenPanel()
openPanel.allowsMultipleSelection = false
openPanel.canChooseDirectories = false
guard openPanel.runModal() == .OK,
let url = openPanel.url
else { return }
self.readFile(from: url)
}
@IBAction func exportAsAction(_ sender: NSMenuItem) {
guard let activeWindow = NSApp.orderedWindows.first,
let viewController = activeWindow.contentViewController as? ViewController
else { return }
let savePanel = NSSavePanel()
let accessoryViewController = AccessoryViewController()
savePanel.accessoryView = accessoryViewController.view
savePanel.isExtensionHidden = true
savePanel.begin { (result) -> Void in
guard result == .OK,
var url = savePanel.url
else { NSSound.beep(); return }
let exportType = accessoryViewController.exportType
url = url.deletingPathExtension()
.appendingPathExtension(exportType.rawValue)
do { try viewController.textureManager.write(to: url) }
catch { displayAlert(message: "File write failed, error: \(error)") }
}
}
func application(_ application: NSApplication, open urls: [URL]) {
urls.forEach { self.readFile(from: $0) }
}
func readFile(from url: URL) {
let storyboard = NSStoryboard(name: "Main", bundle: nil)
guard let windowController = storyboard.instantiateController(withIdentifier: "TextureViewer") as? NSWindowController,
let viewController = windowController.contentViewController as? ViewController
else { displayAlert(message: "ViewController initialization falied"); return }
do {
try viewController.textureManager.read(from: url)
viewController.drawTexture()
}
catch { displayAlert(message: "File read failed, error: \(error)") }
windowController.window?.title = url.lastPathComponent
windowController.showWindow(self)
}
}
|
//
// WeatherAPI.swift
// DailyLifeV2
//
// Created by Lý Gia Liêm on 8/20/19.
// Copyright © 2019 LGL. All rights reserved.
//
import Foundation
import ObjectMapper
struct DarkSkyApi: Decodable, Mappable {
var currently: Currently?
var latitude: Double?
var longitude: Double?
var daily: Daily?
init?(map: Map) {
}
mutating func mapping(map: Map) {
currently <- map["currently"]
latitude <- map["latitude"]
longitude <- map["longitude"]
daily <- map["daily"]
}
}
struct Daily: Decodable, Mappable {
var summary: String?
var icon: String?
var data: [Data]?
init?(map: Map) {
}
mutating func mapping(map: Map) {
summary <- map["summary"]
icon <- map["icon"]
data <- map["data"]
}
}
struct Data: Decodable, Mappable {
var time: Int?
var temperatureMax: Double?
var temperatureMin: Double?
var icon: String?
var precipProbability: Double?
init?(map: Map) {
}
mutating func mapping(map: Map) {
time <- map["time"]
temperatureMax <- map["temperatureMax"]
temperatureMin <- map["temperatureMin"]
icon <- map["icon"]
precipProbability <- map["precipProbability"]
}
}
struct Currently: Decodable, Mappable {
var precipType: String?
var summary: String?
var icon: String?
var nearestStormDistance: Double?
var precipIntensity: Double?
var precipProbability: Double?
var time: Int?
var dewPoint: Double?
var windBearing: Double?
var uvIndex: Double?
var ozone: Double?
var humidity: Double?
var pressure: Double?
var windSpeed: Double?
var cloudCover: Double?
var visibility: Double?
var temperature: Double?
var apparentTemperature: Double?
var windGust: Double?
init?(map: Map) {
}
mutating func mapping(map: Map) {
precipType <- map["precipType"]
summary <- map["summary"]
icon <- map["icon"]
nearestStormDistance <- map["nearestStormDistance"]
precipProbability <- map["precipProbability"]
precipIntensity <- map["precipIntensity"]
time <- map["time"]
dewPoint <- map["dewPoint"]
windBearing <- map["windBearing"]
uvIndex <- map["uvIndex"]
ozone <- map["ozone"]
humidity <- map["humidity"]
pressure <- map["pressure"]
windSpeed <- map["windSpeed"]
cloudCover <- map["cloudCover"]
visibility <- map["visibility"]
temperature <- map["temperature"]
apparentTemperature <- map["apparentTemperature"]
windGust <- map["windGust"]
}
}
|
//
// EachPostTableViewCell.swift
// DrinkWhat
//
// Created by xiqi zhou on 2/7/16.
// Copyright © 2016 writeswift. All rights reserved.
//
import UIKit
class EachPostTableViewCell: UITableViewCell {
@IBOutlet weak var postTitle: UILabel!
@IBOutlet weak var postImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
layer.cornerRadius = 10.0
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// HomeViewController.swift
// Bit Hockey (iOS)
//
// Created by Collin DeWaters on 9/17/17.
// Copyright © 2017 Collin DeWaters. All rights reserved.
//
import UIKit
///`HomeViewController`: first interface the user sees when entering the app.
class RetroHomeViewController: HomeViewController {
//MARK: - `HomeViewController` overrides.
override var isInRetroMode: Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension UIView {
func setCornerRadius(toValue value: CGFloat) {
self.clipsToBounds = true
self.layer.cornerRadius = value
}
}
|
//
// Line.swift
// firstDraw
//
// Created by Terry Lyu on 2/9/17.
// Copyright © 2017 Terry Lyu. All rights reserved.
//
import UIKit
class Line {
var start: CGPoint
var end : CGPoint
var thick : CGFloat
var color: UIColor
init(startPoint:CGPoint, endPoint: CGPoint, startColor: UIColor, startThick : CGFloat){
color = startColor
thick = startThick
start = startPoint
end = endPoint
}
}
|
//
// DataProvider.swift
// PizzaAnimation
//
// Created by Tubik Studio on 8/5/16.
// Copyright © 2016 Tubik Studio. All rights reserved.
//
import UIKit
class DataProvider {
func mockedCategories() -> [TSFoodCategory] {
let pasta = TSFoodCategory(title: NSLocalizedString("P A S T A", comment: ""),
staticImageName: "pasta",
color: UIColor(red: 0.26, green: 0.85, blue: 0.52, alpha: 1.0))
pasta.foodItems = [FoodItem(title:"TURBO RIGATONI ARRABBIATA"),
FoodItem(title:"SPAGHETTI CARBONARA"),
FoodItem(title:"FRESH CRAB SPAGHETTI"),
FoodItem(title:"SQUID & MUSSEL SPAGHETTI NERO")]
let pizza = TSFoodCategory(title: NSLocalizedString("P I Z Z A", comment: ""),
staticImageName: "pizza",
color: UIColor(red: 0.89, green: 0.3, blue: 0.3, alpha: 1.0))
pizza.foodItems = [FoodItem(title:"PIZZA AGILO E OLIO"),
FoodItem(title:"PIZZA ALLA MARINARA"),
FoodItem(title:"PIZZA CON LE COZZE"),
FoodItem(title:"PIZZA ALLE VONGOLE"),
FoodItem(title:"PIZZA MARGHERITA"),
FoodItem(title:"PIZZA REGINA")]
let potatoes = TSFoodCategory(title: NSLocalizedString("P O T A T O E S", comment: ""),
staticImageName: "potatoes",
color: UIColor(red: 1.0, green: 0.7, blue: 0.29, alpha: 1.0))
potatoes.foodItems = [FoodItem(title:"MASHED POTATOES"),
FoodItem(title:"SCALLOPED POTATOES"),
FoodItem(title:"POTATO SOUP"),
FoodItem(title:"SPICE SWEET POTATOES")]
let salads = TSFoodCategory(title: NSLocalizedString("S A L A D S", comment: ""),
staticImageName: "salads",
color: UIColor(red: 0.79, green: 0.46, blue: 0.73, alpha: 1.0))
salads.foodItems = [FoodItem(title:"TOSSED GREEN SALAD"),
FoodItem(title:"CAESAR SALAD"),
FoodItem(title:"FRESH VEGETABLE SALAD"),
FoodItem(title:"FACTORY CHOPPED SALAD"),
FoodItem(title:"CHINESE CHICKEN SALAD"),
FoodItem(title:"LUAU SALAD"),
FoodItem(title:"GRILLED CHICKEN TOSTADA SALAD")]
return [potatoes, pasta, pizza, salads]
}
} |
//
// Label.swift
// AlphabetOrder
//
// Created by Satvik Borra on 12/20/16.
// Copyright © 2016 vborra. All rights reserved.
//
import UIKit
class Label: UILabel{
static let Null = Label(frame: CGRect.zero, text: "")
var outPos: CGPoint!
var inPos: CGPoint!
var neon: Bool = true
init(frame: CGRect, text: String, _outPos: CGPoint = CGPoint.zero, _inPos: CGPoint = CGPoint.zero, textColor: UIColor = UIColor.white, debugFrame: Bool = false, _neon: Bool = true){
outPos = _outPos
inPos = _inPos
neon = _neon
let newFrame = CGRect(origin: outPos, size: frame.size)
super.init(frame: newFrame)
if(debugFrame){
self.layer.borderColor = UIColor.red.cgColor
layer.borderWidth = 5
}
adjustsFontSizeToFitWidth = true
if(neon){
layer.shadowRadius = Neon.shadowRadius
layer.shadowOpacity = Neon.shadowOpacity
layer.shadowOffset = Neon.shadowOffset
layer.masksToBounds = Neon.masksToBounds
}
changeTextColor(color: textColor)
self.text = text
}
func changeTextColor(color: UIColor){
textColor = color
if(neon){
layer.shadowColor = color.cgColor
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func animateIn(time: CGFloat){
UIView.animate(withDuration: TimeInterval(time), animations: {
self.frame.origin = self.inPos
})
}
func animateOut(time: CGFloat){
UIView.animate(withDuration: TimeInterval(time), animations: {
self.frame.origin = self.outPos
})
}
}
|
import Testable
protocol TypeInject {
associatedtype TypeActAs
init()
}
extension TypeInject {
static func createAndInjectType(_ name: String? = nil) -> Self {
Init(Self()) {
TestDependency.register(Inject($0))
TestDependency.register(Inject<TypeActAs>(type(of: $0) as! TypeActAs, name: name))
}
}
}
|
//
// InternetHelper.swift
// ConvertUnitsDark
//
// Created by tyl on 25/6/16.
// Copyright © 2016 strikespark. All rights reserved.
//
import Foundation
//updated for swift 3
class NetworkHelper {
struct ResponseCode {
static let NoJSONData:Int = 700
static let DifficultyParsingJSON:Int = 701
static let ReturnedJSONButFailure:Int = 702
}
static let TimeOutInterval:Double = 10.0
static let sharedInstance = NetworkHelper()
//NSURLSession should be a long lived object that all created NSURLTask use
//One NSURTask Per Request
//more info on this WWDC 2013 session 705
//therefore we create one singleton that will be used by all session task
let session:URLSession
init(){
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = NetworkHelper.TimeOutInterval
sessionConfig.timeoutIntervalForResource = NetworkHelper.TimeOutInterval
//http://www.drdobbs.com/architecture-and-design/memory-leaks-in-ios-7/240168600 stops any memory leaks
sessionConfig.urlCache = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: "URLCache")
session = URLSession(configuration: sessionConfig)
}
open func createNSURLRequest(withString urlString:String, dataBody:AnyObject?, requestMethod:String, isJSON:Bool) -> NSMutableURLRequest?{
let url:URL? = URL(string: urlString)
let urlRequest:NSMutableURLRequest
if let url = url {
urlRequest = NSMutableURLRequest(url:url)
} else {
print("DEBUG url string cannot be converted to url")
return nil
}
if isJSON {
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
if let dataBodyData = dataBody as? Data {
urlRequest.httpBody = dataBodyData
}
} else {
urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
// if let dataBody:AnyObject = dataBody { //swift 2
// urlRequest.httpBody = dataBody.data(using: String.Encoding.utf8)
// }
if let dataString:String = dataBody as? String {
urlRequest.httpBody = dataString.data(using: .utf8)!
}
}
return urlRequest
}
open func request(mutableURLRequest:NSMutableURLRequest, success: @escaping (_ data:Data?,_ response:URLResponse?,_ error:Error?)->Void, failure: @escaping (_ data:Data?,_ response:URLResponse?,_ error:Error?,_ responseCode:Int)->Void){
let dataTask:URLSessionDataTask = NetworkHelper.sharedInstance.session.dataTask(with: mutableURLRequest as URLRequest, completionHandler: { (dataInternal, responseInteral, errorInternal) in
let HTTPResponse:HTTPURLResponse? = responseInteral as? HTTPURLResponse
let responseCode:Int
if let HTTPResponse:HTTPURLResponse = HTTPResponse {
responseCode = HTTPResponse.statusCode
} else {
responseCode = 0
}
if errorInternal != nil || responseCode != 200 {
// failure(data: dataInternal,response: responseInteral,error: errorInternal,responseCode: responseCode)
failure(dataInternal,responseInteral,errorInternal as NSError?,responseCode)
} else {
// success(data: dataInternal, response: responseInteral,error: errorInternal)
success(dataInternal,responseInteral,errorInternal)
}
})
dataTask.resume()
}
//combination of two methods above
//This takes a urlstring that can either be a JSON or not
open func request(urlString:String, dataBody:AnyObject?, requestMethod:String, isJSON:Bool, success:@escaping (_ data:Data?, _ response:URLResponse?, _ error:Error?)->Void, failure:@escaping (_ data:Data?, _ response:URLResponse?, _ error:Error?, _ responseCode:Int)->Void){
let urlRequst:NSMutableURLRequest? = createNSURLRequest(withString: urlString, dataBody: dataBody, requestMethod: requestMethod, isJSON: isJSON)
if let urlRequst = urlRequst {
request(mutableURLRequest: urlRequst, success: success, failure: failure)
}
}
open func jsonBaseRequest(urlString:String,dataBody:AnyObject?, requestMethod:String, success:@escaping (_ json:Any, _ response:URLResponse?, _ error:NSError?)->Void, failure:@escaping (_ json:Any?, _ response:URLResponse?, _ error:Error?, _ responseCode:Int)->Void){
request(urlString:urlString,dataBody: dataBody,requestMethod:requestMethod,isJSON:true,
success: {(dataInternal:Data?, responseInternal:URLResponse?, errorInternal:Error?)->Void in
guard let dataInternal = dataInternal else {
failure(nil,responseInternal,nil,ResponseCode.NoJSONData)
return
}
do {
let json:Any = try JSONSerialization.jsonObject(with: dataInternal, options: .mutableContainers )
success(json, responseInternal, nil)
} catch let JSONError as NSError{
failure(dataInternal as AnyObject?,responseInternal,JSONError,ResponseCode.DifficultyParsingJSON)
return
}
},
failure: {(dataInternal:Data?, responseInternal:URLResponse?, errorInternal:Error?,responseCodeInternal:Int )->Void in
guard let dataInternal = dataInternal else {
failure(nil,responseInternal,nil,responseCodeInternal)
return
}
do {
let json:Any = try JSONSerialization.jsonObject(with: dataInternal, options: .mutableContainers )
failure(json, responseInternal, nil,responseCodeInternal)
} catch let JSONError{
failure(nil,responseInternal,JSONError,responseCodeInternal)
return
}
}
)
}
open func jsonGetRequest(urlString:String,success:@escaping (_ json:Any, _ response:URLResponse?, _ error:NSError?)->Void, failure:@escaping (_ json:Any?, _ response:URLResponse?, _ error:Error?, _ responseCode:Int)->Void){
jsonBaseRequest(urlString: urlString, dataBody: nil, requestMethod: "GET", success: success, failure: failure)
}
open func jsonPost(urlString:String, databody:AnyObject?, success:@escaping (_ json:Any, _ response:URLResponse?, _ error:Error?)->Void, failure:@escaping (_ json:Any?, _ response:URLResponse?, _ error:Error?, _ responseCode:Int)->Void){
jsonBaseRequest(urlString: urlString, dataBody: databody, requestMethod: "POST", success: success, failure: failure)
}
open func jsonDelete(urlString:String, success:@escaping (_ json:Any, _ response:URLResponse?, _ error:NSError?)->Void, failure:@escaping (_ json:Any?, _ response:URLResponse?, _ error:Error?, _ responseCode:Int)->Void){
jsonBaseRequest(urlString: urlString, dataBody: nil, requestMethod: "DELETE", success: success, failure: failure)
}
//download To Do
open func download(){
}
}
|
//
// LRLPBCell.swift
// LRLPhotoBrowserDemo
//
// Created by liuRuiLong on 2017/6/19.
// Copyright © 2017年 codeWorm. All rights reserved.
//
import UIKit
import Kingfisher
import MBProgressHUD
class LRLPBCell: UICollectionViewCell{
lazy var showView: LRLPBImageView = self.initialShowView()
func initialShowView() -> LRLPBImageView{
return LRLPBImageView(frame: CGRect.zero)
}
func outZoom() {
showView.outZoom()
}
func inZoom() {
showView.inZoom()
}
var zooming:Bool{
get{
return showView.zooming
}
}
var zoomToTop: Bool{
get{
return showView.zoomToTop
}
}
func endDisplay(){
showView.endDisplay()
}
func changeTheImageViewLocationWithOffset(offset: CGFloat) {
if !zooming{
showView.setImageTransform(transform: CGAffineTransform(translationX: self.bounds.width * offset - 150.0 * offset, y: 0))
}
}
}
extension UICollectionViewCell{
class func reuseIdentifier() -> String{
return NSStringFromClass(self)
}
}
class LRLPBImageCell: LRLPBCell{
override init(frame: CGRect) {
super.init(frame: frame)
showView.frame = self.contentView.bounds
self.contentView.addSubview(showView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setData(imageUrl: String, placeHolder: UIImage?){
let url = URL(string: imageUrl)
showView.setImage(with: url, placeholder:placeHolder)
}
func setData(imageName: String) {
showView.setImage(image: UIImage(named: imageName) ?? UIImage(named: "placeHolder.jpg")!)
}
func setData(image: UIImage) {
showView.setImage(image: image)
}
}
class LRLPBVideoCell: LRLPBCell{
override func initialShowView() -> LRLPBImageView {
return LRLPBVideoView(frame: CGRect.zero)
}
var inShowView: LRLPBVideoView{
get{
return showView as! LRLPBVideoView
}
}
override init(frame: CGRect) {
super.init(frame: frame)
showView.frame = self.contentView.bounds
self.contentView.addSubview(showView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setData(videoUrl: URL, placeHolder: UIImage?){
inShowView.setVideoUrlStr(url: videoUrl, palceHolder: placeHolder)
}
}
|
//
// singlePlayer.swift
// dervishi_Daniel_Matching
//
// Created by Period Three on 2019-12-03.
// Copyright © 2019 Period Three. All rights reserved.
//
import Foundation
class singlePlayer: <#super class#> {
<#code#>
}
|
//
// LPMainViewController.swift
// fakeDouyu
//
// Created by wslp0314 on 2017/8/16.
// Copyright © 2017年 goout. All rights reserved.
//
import UIKit
class LPMainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
addChildVC(vc: "Home")
addChildVC(vc: "Live")
addChildVC(vc: "Follow")
addChildVC(vc: "Profile")
}
private func addChildVC(vc : String) {
//通过 storyName 加入 tabbar 的 根
let childHome = UIStoryboard(name: vc, bundle: nil).instantiateInitialViewController()!
addChildViewController(childHome)
}
}
|
//
// LoginViewController.swift
// Appoint
//
// Created by Aman Jaiswal on 07/04/20.
// Copyright © 2020 Aman Jaiswal. All rights reserved.
//
import UIKit
import Firebase
class LoginViewController: UIViewController {
// Start of connection of IBOutlets of textfields and button in LoginViewController!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var errorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Hides keyboard when tapped near fields. Reference:- keyboardOff.swift
self.hideKeyboardWhenTappedAround()
// Do any additional setup after loading the view.
// Adds image icon to the right of the field.
emailTextField.addRightView(image: #imageLiteral(resourceName: "logout.png"))
passwordTextField.addRightView(image: #imageLiteral(resourceName: "logout.png"))
}
// Toggling navigation bar.Turn on and off navigation bar wherever needed.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Hide the Navigation Bar.
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Show the Navigation Bar.
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
//Tap on login Button to transist user to TabBarViewController as a landing page.
@IBAction func loginTapped(_ sender: Any) {
// TODO: Validate Text Fields
// Create cleaned versions of the text field
let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let password = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
// Signing in the user
Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
if error != nil {
// Couldn't sign in
self.errorLabel.text = error!.localizedDescription
self.errorLabel.alpha = 1
}
else {
// let HomeViewController = self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.HomeViewController) as? HomeViewController
//
// self.view.window?.rootViewController = HomeViewController
// self.view.window?.makeKeyAndVisible()
// code for calling TabBarViewController as a landing page.
let tabBarViewController = self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.tabBarViewController) as? TabBarViewController
self.view.window?.rootViewController = tabBarViewController
self.view.window?.makeKeyAndVisible()
}
}
}
}
|
//
// CategoryDetailCollectionViewCell.swift
// Asoft-Intern-Final-Demo
//
// Created by Danh Nguyen on 1/3/17.
// Copyright © 2017 Danh Nguyen. All rights reserved.
//
import UIKit
protocol PushViewController {
func pushViewControlerWithIdentifierSegue(identifier: String, food: Food)
}
class CategoryDetailCollectionViewCell: UICollectionViewCell {
//#MARK: - Outlet
@IBOutlet weak var mainTableView: UITableView!
//#MARK: - Define properties
lazy internal var myContentOffsetY: CGFloat = 0.0
var pushDelegate: PushViewController?
var foods: [Food] = []
//#MARK: - Set up
override func awakeFromNib() {
super.awakeFromNib()
self.mainTableView.dataSource = self
self.mainTableView.delegate = self
self.mainTableView.tableFooterView = UIView(frame: CGRect.zero)
}
}
//#MARK: - UITableView DataSource
extension CategoryDetailCollectionViewCell: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.foods.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.kIdentifierCategoryCustomDetailTableViewCell, for: indexPath) as! CategoryDetailTableViewCell
cell.selectionStyle = .none
cell.containerView.clipsToBounds = true
cell.containerView.layer.cornerRadius = 4
cell.layer.shadowColor = UIColor.black.cgColor
cell.layer.shadowOpacity = 0.3
cell.layer.shadowOffset = CGSize.zero
cell.layer.shadowRadius = 1
cell.mainImageView.image = UIImage(named: self.foods[indexPath.row].image)
cell.nameLabel.text = self.foods[indexPath.row].name
cell.timeLabel.text = "\(self.foods[indexPath.row].timeToPerform) min"
return cell
}
}
//#MARK: - UITableView Delegate
extension CategoryDetailCollectionViewCell: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 180
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let pushDelegate = self.pushDelegate {
pushDelegate.pushViewControlerWithIdentifierSegue(identifier: AppSegueIdentifiers.kIdentifierSegueCategoryToRecipeChoosen, food: self.foods[indexPath.row])
}
}
}
//#MARK: - UIScrollView Delegate
extension CategoryDetailCollectionViewCell {
}
|
//
// HabitDetailsViewController.swift
// MyHabits
//
// Created by Natali Malich on 21.08.2021.
//
import UIKit
class HabitDetailsViewController: UIViewController {
private var habit: Habit
private lazy var tableView: UITableView = {
let table = UITableView()
table.translatesAutoresizingMaskIntoConstraints = false
return table
}()
private lazy var headerTable: UILabel = {
let label = UILabel()
label.text = "АКТИВНОСТЬ"
label.font = .footnote
label.textColor = .systemGray
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private lazy var cell = "habitDetailsID"
init (habit: Habit) {
self.habit = habit
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
setupViews()
setupConstraints()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
navigationItem.title = "\(habit.name)"
}
}
extension HabitDetailsViewController {
private func setupNavigationBar() {
navigationItem.title = "\(habit.name)"
navigationItem.largeTitleDisplayMode = .never
navigationController?.navigationBar.tintColor = .purpleColor
let rightBarButtonItem = UIBarButtonItem(title: "Править", style: .done, target: self, action: #selector(onEditHabit))
navigationItem.rightBarButtonItem = rightBarButtonItem
}
}
extension HabitDetailsViewController {
@objc func onEditHabit() {
let habitVC = HabitViewController(habit: habit)
habitVC.onRemove = { [weak self] in
self?.navigationController?.popToRootViewController(animated: false)
}
let habitNavigationVC = UINavigationController(rootViewController: habitVC)
habitNavigationVC.modalPresentationStyle = .fullScreen
present(habitNavigationVC, animated: true, completion: nil)
}
}
extension HabitDetailsViewController {
private func setupViews() {
view.addSubview(tableView)
tableView.addSubview(headerTable)
tableView.backgroundColor = .lightGrayColor
tableView.dataSource = self
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "habitDetailsID")
}
}
extension HabitDetailsViewController {
private func setupConstraints() {
[
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
headerTable.topAnchor.constraint(equalTo: tableView.topAnchor, constant: 22),
headerTable.leadingAnchor.constraint(equalTo: tableView.leadingAnchor, constant: 16)
]
.forEach {$0.isActive = true}
}
}
extension HabitDetailsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
HabitsStore.shared.dates.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "habitDetailsID", for: indexPath)
let habitIndex = abs(indexPath.row - HabitsStore.shared.dates.count + 1)
cell.textLabel?.text = HabitsStore.shared.trackDateString(forIndex: habitIndex)
let date = HabitsStore.shared.dates[habitIndex]
if HabitsStore.shared.habit(habit, isTrackedIn: date) {
cell.accessoryType = UITableViewCell.AccessoryType.checkmark
cell.tintColor = .purpleColor
}
return cell
}
}
extension HabitDetailsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return headerTable
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 47
}
}
|
//
// BaseTableViewCell.swift
// BaseViewControllers
//
// Created by acalism on 16-9-29.
// Copyright © 2016 acalism. All rights reserved.
//
import UIKit
class BaseTableViewCell<CellDataModel>: UITableViewCell, CellCommonPart, CellConfgigurable {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
loadContentView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadContentView()
}
func loadContentView() {
//selectionStyle = .none
}
var specialHighlightedArea: UIView? = nil
var shouldTintBackgroundWhenSelected = true
weak var tableView: UITableView? = nil
weak var collectionView: UICollectionView? = nil
weak var hostViewController: UIViewController? = nil // cell有自定义的action时,请遵守ScrollViewCellPerformActionHost 协议
// override func setSelected(_ selected: Bool, animated: Bool) {
// onSelected(selected)
// }
// override func setHighlighted(_ highlighted: Bool, animated: Bool) {
// onSelected(highlighted)
// }
// override var isHighlighted: Bool { // make lightgray background show immediately(使灰背景立即出现)
// willSet {
// onSelected(newValue)
// }
// }
// override var isSelected: Bool { // keep lightGray background until unselected (保留灰背景)
// willSet {
// onSelected(newValue)
// }
// }
func onSelected(_ newValue: Bool) {
defaultOnSelected(newValue)
}
// MARK: - CellConfigurable
var model: CellDataModel? = nil
/// override 时需调用super
func configure(model: CellDataModel?) {
self.model = model
}
}
|
//
// PlanNoElementsDialog.swift
// KayakFirst Ergometer E2
//
// Created by Balazs Vidumanszki on 2017. 07. 07..
// Copyright © 2017. Balazs Vidumanszki. All rights reserved.
//
import Foundation
class PlanNoElementsDialog: BaseDialog {
//MAK: init
init() {
super.init(title: nil, message: getString("dialog_plan_no_elements"))
showPositiveButton(title: getString("other_ok"))
}
}
|
//
// Regulation.swift
// SignalPhotoEditor
//
// Created by Anastasia Holovash on 02.12.2020.
//
import UIKit
extension CoreSignalPhotoEditor {
static var filterCollectionModels: [FilterModel] = [
FilterModel(image: UIImage(named: "Brightness")!, filter: BrightnessRegulation()),
FilterModel(image: UIImage(named: "Saturation")!, filter: SaturationRegulation()),
FilterModel(image: UIImage(named: "Contrast")!, filter: ContrastRegulation()),
FilterModel(image: UIImage(named: "Exposure")!, filter: ExposureAdjustRegulation()),
FilterModel(image: UIImage(named: "Gamma")!, filter: GammaAdjustRegulation()),
FilterModel(image: UIImage(named: "Hue")!, filter: HueAdjustRegulation()),
FilterModel(image: UIImage(named: "Temperature")!, filter: TemperatureRegulation()),
FilterModel(image: UIImage(named: "Tint")!, filter: TintRegulation()),
FilterModel(image: UIImage(named: "Vibrance")!, filter: VibranceRegulation()),
FilterModel(image: UIImage(named: "Vignette")!, filter: VignetteFilter()),
]
}
|
//
// Photo.swift
// Virtual Tourist
//
// Created by Johan Smet on 09/08/15.
// Copyright (c) 2015 Justcode.be. All rights reserved.
//
import Foundation
import CoreData
@objc(Photo)
class Photo : NSManagedObject {
@NSManaged var flickrUrl : String
@NSManaged var localUrl : String?
@NSManaged var location : Pin
////////////////////////////////////////////////////////////////////////////////
//
// initialisers
//
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
init(flickrUrl : String, location : Pin, context: NSManagedObjectContext) {
// Core Data
let entity = NSEntityDescription.entityForName("Photo", inManagedObjectContext: context)!
super.init(entity: entity, insertIntoManagedObjectContext: context)
// properties
self.flickrUrl = flickrUrl
self.location = location
}
////////////////////////////////////////////////////////////////////////////////
//
// NSManagedObject overrides
//
override func prepareForDeletion() {
// also delete the image file when a photo is removed from core data
if let localUrl = self.localUrl {
let documentsDirectory: AnyObject = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
let path = documentsDirectory.stringByAppendingPathComponent(localUrl)
do {
try NSFileManager.defaultManager().removeItemAtPath(path)
} catch _ {
}
}
}
}
|
//
// COAcitvityButton.swift
// CoAssetsApps
//
// Created by Linh NGUYEN on 3/18/16.
// Copyright © 2016 TruongVO07. All rights reserved.
//
import UIKit
class COAcitvityButton: CORedButton {
var animating = false
var title: String?
weak var activityIndicator: UIActivityIndicatorView?
override func viewDidLoad() {
super.viewDidLoad()
let indicator = UIActivityIndicatorView()
indicator.activityIndicatorViewStyle = .White
indicator.hidesWhenStopped = true
indicator.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(indicator)
let heightCT = NSLayoutConstraint(item: indicator, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 1.0, constant: -10)
let radioCT = NSLayoutConstraint(item: indicator, attribute: .Width, relatedBy: .Equal, toItem: indicator, attribute: .Height, multiplier: 1.0, constant: 0)
let centerX = NSLayoutConstraint(item: indicator, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0)
let centerY = NSLayoutConstraint(item: indicator, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0)
indicator.addConstraints([radioCT])
self.addConstraints([heightCT, centerX, centerY])
self.activityIndicator = indicator
}
func startAnimating() {
self.title = self.titleForState(.Normal)
self.setTitle("", forState: .Normal)
self.activityIndicator?.startAnimating()
}
func stopAnimating() {
self.activityIndicator?.stopAnimating()
self.setTitle(self.title, forState: .Normal)
}
}
|
//
// ViewController.swift
// Facebook Political Ad Collector
//
// Created by Ryan Govostes on 2/13/18.
// Copyright © 2018 ProPublica. All rights reserved.
//
import Cocoa
import SafariServices
import WebKit
class ViewController: NSViewController {
private var isSafariExtensionEnabled = false
@IBOutlet var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Start monitoring for state changes
self.watchSafariExtensionState()
// Load the embedded HTML file
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "content")
// let dir = Bundle.main.resourceURL!.appendingPathComponent("content", isDirectory: true)
webView.loadFileURL(url!, allowingReadAccessTo: url!)
}
}
// MARK: - Safari State
extension ViewController {
private func watchSafariExtensionState() {
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
SFSafariExtensionManager.getStateOfSafariExtension(withIdentifier: "org.propublica.FacebookAdCollector.Extension") { state, error in
guard error == nil, state != nil else {
NSLog("Could not get extension state: \(error?.localizedDescription ?? "unknown")")
return
}
if state!.isEnabled != self.isSafariExtensionEnabled {
self.isSafariExtensionEnabled = state!.isEnabled
self.safariExtensionStateChanged()
}
}
}
}
private func safariExtensionStateChanged() {
guard webView != nil else { return }
DispatchQueue.main.async {
self.webView.evaluateJavaScript("document.body.innerText = '\(self.isSafariExtensionEnabled)'")
}
}
}
// MARK: - Resize to Fit
extension ViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.getContentSize() { size in
self.view.window!.setContentSize(size)
self.view.window!.center()
}
}
}
|
//
// newTabbarController.swift
// TabbarDesignImplementation
//
// Created by Superpower on 17/08/20.
// Copyright © 2020 iMac superpower. All rights reserved.
//
import Foundation
import UIKit
var StartText : String!
class newTabbarController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: ***** Variable and outlets *****
// outlets
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var headerTextLabel: UILabel!
@IBOutlet weak var tabbarTableView: UITableView!
// Variables
var textboxCellPlaceHolderArray = ["Player Name", "Sport", "Year", "Set", "Variation/Color", "Card #"]
var switchLabelPlaceHolderArray = ["Rookie", "Autograph", "Patch", "Scanned on "]
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let saveCard_key = "SaveCards_\(selected_CardID)"
print("newTabbarController saveCard_key: \(saveCard_key)")
if defaults.data(forKey: saveCard_key) != nil {
CardDetails = LoadCards.loadCardsDetails(Card_ID: selected_CardID)
print("CardDetails.number: \(CardDetails.Card_ID)")
print("CardDetails.PlayerName: \(CardDetails.PlayerName)")
} else {
print("NO CARD DETAILS AVAILABLE")
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabbarTableView.delegate = self
self.tabbarTableView.dataSource = self
tabbarTableView.reloadData()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
self.view.endEditing(true)
}
@IBAction func backBtnTapped(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.textboxCellPlaceHolderArray.count + self.switchLabelPlaceHolderArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let PlaceHolderArrayCount = textboxCellPlaceHolderArray.count - 1
let SwitchStartingPoint = (textboxCellPlaceHolderArray.count + switchLabelPlaceHolderArray.count) - 1
switch indexPath.row {
case 0...PlaceHolderArrayCount:
let cell = tabbarTableView.dequeueReusableCell(withIdentifier: "cellWithTextbox") as! cellWithTextbox
cell.placeHolderLabel.text = self.textboxCellPlaceHolderArray[indexPath.row]
cell.textFieldInsideCell.placeholder = "Enter \(self.textboxCellPlaceHolderArray[indexPath.row])"
cell.textFieldInsideCell.delegate = self
print("Enter \(self.textboxCellPlaceHolderArray[indexPath.row])")
print("\(indexPath.row)")
if indexPath.row == 1 {
cell.textFieldInsideCell.isEnabled = false
cell.textFieldInsideCell.text = CardDetails.Sport
} else if indexPath.row == 2 {
cell.textFieldInsideCell.isEnabled = false
cell.textFieldInsideCell.text = CardDetails.Year
} else if indexPath.row == 3 {
cell.textFieldInsideCell.isEnabled = false
cell.textFieldInsideCell.text = CardDetails.Set
} else if indexPath.row == 0 {
CardDetails = LoadCards.loadCardsDetails(Card_ID: selected_CardID)
print("CellforRow CardDetails.PlayerName: \(CardDetails.PlayerName)")
cell.textFieldInsideCell.text = CardDetails.PlayerName
cell.textFieldInsideCell.isEnabled = true
cell.textFieldInsideCell.viewWithTag(indexPath.row)
} else if indexPath.row == 4 {
print("CellforRow CardDetails.VariationColour: \(CardDetails.VariationColour)")
cell.textFieldInsideCell.viewWithTag(indexPath.row)
cell.textFieldInsideCell.text = CardDetails.VariationColour
cell.textFieldInsideCell.isEnabled = true
} else if indexPath.row == 5 {
print("CellforRow CardDetails.CardNo: \(CardDetails.CardNo)")
cell.textFieldInsideCell.viewWithTag(indexPath.row)
cell.textFieldInsideCell.text = CardDetails.CardNo
cell.textFieldInsideCell.isEnabled = true
} else {
cell.textFieldInsideCell.isEnabled = true
}
return cell
case textboxCellPlaceHolderArray.count...SwitchStartingPoint:
let cell = tabbarTableView.dequeueReusableCell(withIdentifier: "cellWithSwitchButton") as! cellWithSwitchButton
let count = indexPath.row - textboxCellPlaceHolderArray.count
cell.labelSwitchCell.text = self.switchLabelPlaceHolderArray[count]
// cell.labelSwitchCell.viewWithTag(indexPath.row)
switch indexPath.row {
case 6:
cell.switchInsideCell.isHidden = false
if CardDetails.Rookie == true {
cell.switchInsideCell.isOn = true
} else {
cell.switchInsideCell.isOn = false
}
case 7:
cell.switchInsideCell.isHidden = false
if CardDetails.Autograph == true {
cell.switchInsideCell.isOn = true
} else {
cell.switchInsideCell.isOn = false
}
case 8:
cell.switchInsideCell.isHidden = false
if CardDetails.Patch == true {
cell.switchInsideCell.isOn = true
} else {
cell.switchInsideCell.isOn = false
}
case 9:
cell.switchInsideCell.isHidden = true
default:
break
}
return cell
default:
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tabbarTableView.dequeueReusableCell(withIdentifier: "cellWithTextbox") as! cellWithTextbox
switch indexPath.row {
case 0:
print("Player Name Tapped")
case 1:
CellTapped = "Sports"
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SetViewController") as! SetViewController
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: true, completion: nil)
print("Sport tapped")
case 2:
CellTapped = "Year"
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SetViewController") as! SetViewController
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: true, completion: nil)
print("year tapped")
case 3:
CellTapped = "SetView"
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SetViewController") as! SetViewController
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: true, completion: nil)
print("set tapped")
default:
print("other Actions")
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
}
// MARK: ***** Extention TableView delegate *****
// MARK: ***** TextField Delegate Functions *****
var playerNameString : String!
var Variation : String!
var CardNumbers: String!
extension newTabbarController: UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
func textFieldDidBeginEditing(_ textField: UITextField) {
// let cell = tabbarTableView.dequeueReusableCell(withIdentifier: "cellWithTextbox") as! cellWithTextbox
let cell: UITableViewCell = textField.superview?.superview as! UITableViewCell
var table: UITableView = cell.superview as! UITableView
let textfieldIndexPath = table.indexPath(for: cell)?.row
print("textfieldIndexPath -->> textFieldDidBeginEditing: \(textfieldIndexPath)")
print(textField.text)
switch textfieldIndexPath {
case 0:
print("playerNameString: \(textField.text)")
playerNameString = textField.text
case 4:
print("Variation: \(textField.text)")
Variation = textField.text
case 5:
print("CardNumbers: \(textField.text)")
CardNumbers = textField.text
default:
break
}
print("Editing Ended")
}
func textFieldDidEndEditing(_ textField: UITextField) {
print(textField.text)
let cell: UITableViewCell = textField.superview?.superview as! UITableViewCell
var table: UITableView = cell.superview as! UITableView
let textfieldIndexPath = table.indexPath(for: cell)?.row
print("textfieldIndexPath -->> textFieldDidEndEditing : \(textfieldIndexPath)")
switch textfieldIndexPath {
case 0:
print(textField.text)
print(StartText)
Homedetails.Name = textField.text
SaveHome(HomeMaster: Homedetails, cardID: selected_CardID)
CardDetails.PlayerName = textField.text
print("Name Saved under Home Details and CardDetails after editing")
SaveCards.saveCardsvalue(CardsValue: CardDetails, Card_ID: selected_CardID)
case 4:
print(textField.text)
CardDetails.VariationColour = textField.text
print("Variation Colour Saved in Card Details after editing")
SaveCards.saveCardsvalue(CardsValue: CardDetails, Card_ID: selected_CardID)
case 5:
print(textField.text)
CardDetails.CardNo = (textField.text ?? "0")
print("CardNo Saved in Card Details after editing")
SaveCards.saveCardsvalue(CardsValue: CardDetails, Card_ID: selected_CardID)
default:
break
}
print("Editing Ended")
}
}
// MARK: ***** TableViewCell Class Functions *****
class cellWithTextbox: UITableViewCell{
@IBOutlet weak var placeHolderLabel: UILabel!
@IBOutlet weak var textFieldInsideCell: UITextField!
static var identifier = "cellWithTextbox"
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = .none
}
}
class cellWithSwitchButton: UITableViewCell {
@IBOutlet weak var labelSwitchCell: UILabel!
@IBOutlet weak var switchInsideCell: UISwitch!
static var identifier = "cellWithSwitchButton"
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = .none
switchInsideCell.addTarget(self, action: #selector(SwitchChanged), for: .valueChanged)
}
@objc func SwitchChanged(mySwitch: UISwitch) {
let value = mySwitch.isOn
print("Switch value: \(value)")
let cell: UITableViewCell = mySwitch.superview?.superview as! UITableViewCell
let table: UITableView = cell.superview as! UITableView
let switchIndexPath = table.indexPath(for: cell)?.row
print("switchIndexPath -->> switchDidBeginEditing: \(switchIndexPath)")
switch switchIndexPath {
case 6:
CardDetails.Rookie = value
SaveCards.saveCardsvalue(CardsValue: CardDetails, Card_ID: selected_CardID)
case 7:
CardDetails.Autograph = value
SaveCards.saveCardsvalue(CardsValue: CardDetails, Card_ID: selected_CardID)
case 8:
CardDetails.Patch = value
SaveCards.saveCardsvalue(CardsValue: CardDetails, Card_ID: selected_CardID)
default:
break
}
}
}
// MARK: ***** extention UIView Top and Bottom border *****
|
import XCTest
import ZenSMTPTests
var tests = [XCTestCaseEntry]()
tests += ZenSMTPTests.allTests()
XCTMain(tests)
|
//
// ViewController.swift
// HTN'19
//
// Created by Pavitra Kurseja on 2019-09-14.
// Copyright © 2019 Pavitra Kurseja. All rights reserved.
//
import UIKit
import Vision
import AVFoundation
import Foundation
class ViewController: UIViewController,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
@IBOutlet weak var myButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func photoLibrary()
{
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = .photoLibrary //.camera
self.present(myPickerController, animated: true, completion: nil)
}
}
@IBAction func openCamera(_ sender: Any) {
photoLibrary()
}
// func launchcamera(press:UILongPressGestureRecognizer)
// {
// if press.state = .began
// { }
//
// Callback function for what happens in your main view
// controller after the photo library view controller returns
// after you picked an image.
func imagePickerController(
_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
print("A")
picker.dismiss(animated: true, completion: nil)
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
print("B")
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFit
let scaledHeight = view.frame.width / image.size.width * image.size.height
imageView.frame = CGRect(x: 0, y: 250, width: view.frame.width, height: scaledHeight)
imageView.backgroundColor = .white
view.addSubview(imageView)
let request = VNDetectFaceRectanglesRequest { (req, err) in
if let err = err {
print("Failed to detect faces:", err)
return
}
req.results?.forEach({ (res) in
DispatchQueue.main.async {
guard let faceObservation = res as? VNFaceObservation else { return }
let x = self.view.frame.width * faceObservation.boundingBox.origin.x
let height = scaledHeight * faceObservation.boundingBox.height
let y = 250 + scaledHeight * (1 - faceObservation.boundingBox.origin.y) - height
let width = self.view.frame.width * faceObservation.boundingBox.width
let redView = UIView()
redView.backgroundColor = .red
redView.alpha = 0.4
redView.frame = CGRect(x: x, y: y, width: width, height: height)
self.view.addSubview(redView)
print(faceObservation.boundingBox)
}
})
}
guard let cgImage = image.cgImage else { return }
DispatchQueue.global(qos: .background).async {
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
do {
try handler.perform([request])
} catch let reqErr {
print("Failed to perform request:", reqErr)
}
}
}
}
func speak(message: String) {
var speechUtterance: AVSpeechUtterance = AVSpeechUtterance(message)
speechUtterance.voice = AVSpeechSynthesisVoice(language: "en-US")
speechSynthesizer.speakUtterance(speechUtterance)
}
func readJSONFromFile(fileName: String) -> Any? {
var json: Any?
if let path = Bundle.main.path(forResource: fileName, ofType: "json") {
do {
let fileUrl = URL(fileURLWithPath: path)
// Getting data from JSON file using the file URL
let data = try Data(contentsOf: fileUrl, options: .mappedIfSafe)
json = try? JSONSerialization.jsonObject(with: data)
} catch {
return
}
}
return json
}
} |
import Foundation
/**
https:adventofcode.com/2019/day/9
*/
enum Day09 {
static func solve() {
let input = Input.get("09-Input.txt")
print("Result Day 9 - Part One: \(intcodeProgramForPart1(input: input))")
print("Result Day 9 - Part Two: \(intcodeProgramForPart2(input: input))")
}
private static func intcodeProgramForPart1(input: String) -> String {
let memory = prepareInput(input: input)
let computer = Computer(memory: memory)
let output = computer.runProgramm(input: 1)!
assert(output == 2399197539)
return String(output)
}
private static func intcodeProgramForPart2(input: String) -> String {
let memory = prepareInput(input: input)
let computer = Computer(memory: memory)
let output = computer.runProgramm(input: 2)!
assert(output == 35106)
return String(output)
}
}
extension Day09 {
private static func prepareInput(input: String) -> [Int] {
return input.components(separatedBy: ",")
.compactMap { Int($0) }
}
}
|
//
// SubmitButton.swift
// WatNi
//
// Created by 홍창남 on 2020/01/19.
// Copyright © 2020 hcn1519. All rights reserved.
//
import Foundation
import UIKit
class SubmitButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setupButton()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupButton()
}
override var isEnabled: Bool {
didSet {
updateBackgroundColor()
}
}
private func setupButton() {
self.setTitleColor(.white, for: .normal)
self.setTitleColor(WNColor.black5, for: .disabled)
self.layer.cornerRadius = 4
updateBackgroundColor()
}
private func updateBackgroundColor() {
if isEnabled {
layer.backgroundColor = WNColor.primaryRed.cgColor
} else {
layer.backgroundColor = WNColor.gray.cgColor
}
}
}
|
//
// Bundle+Tags.swift
// Tags
//
// Created by Tom Clark on 2017-07-23.
// Copyright © 2017 Fluiddynamics. All rights reserved.
//
import Foundation
extension Bundle {
class var tagBundle: Bundle? {
return Bundle(identifier: "ca.Fluiddynamics.Tags")
}
}
|
//
// ViewController.swift
// SKCalenderView
//
// Created by Subrat Kheti on 27/09/20.
// Copyright © 2020 Subrat Kheti. All rights reserved.
//
import UIKit
class CalenderViewController: UIViewController {
@IBOutlet weak var calenderBannerView: CalenderBannerView!
@IBOutlet weak var collectionView: CalenderCollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.calenderBannerView.delegate = self
}
}
extension CalenderViewController: CalendarDelegate {
func calendarUpdateAction(date: Date) {
self.collectionView.updateCalender(date: date)
}
}
|
//
// ViewController.swift
// NabeatuRe
//
// Created by 野崎絵未里 on 2019/06/13.
// Copyright © 2019年 野崎絵未里. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var image: UIImageView!
var number:Int! = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func nabe(_ sender: Any) {
number += 1
label.text = String(number)
if number % 3 == 0 {
image.image = UIImage(named: "mask.png")
} else {
image.image = UIImage(named: "images-6.jpeg")
}
}
@IBAction func atu(_ sender: Any) {
number = 0
label.text = String(number)
image.image = UIImage(named: "images-5.jpeg")
}
}
|
//
// TwitterUser+CoreDataClass.swift
// TwitterTag
//
// Created by shashank kannam on 5/24/17.
// Copyright © 2017 developer. All rights reserved.
//
import Foundation
import Twitter
import CoreData
public class TwitterUser: NSManagedObject {
class func findOrCreateTwitterUser(matching twitterInfo: Twitter.User, in context: NSManagedObjectContext) throws -> TwitterUser {
let request: NSFetchRequest<TwitterUser> = TwitterUser.fetchRequest()
request.predicate = NSPredicate(format: "handle = %@", twitterInfo.screenName)
do {
let matches = try context.fetch(request)
if matches.count > 0 {
assert(matches.count == 1, "TwitterUser: findOrCreateTwitterUser -- database inconsistency")
return matches[0]
}
} catch {
throw error
}
let tweet = TwitterUser(context: context)
tweet.handle = twitterInfo.screenName
tweet.name = twitterInfo.name
return tweet
}
}
|
import Foundation
import TSCUtility
enum Parser {
struct Result {
let projectPath: String
let outputURL: Foundation.URL
let topLevelEnumName: String
let targetName: String?
let locale: String
}
static func parse() throws -> Result {
let exampleUsageString = "$PROJECT_FILE_PATH $PROJECT_DIR/$PROJECT_NAME"
let parser = ArgumentParser(usage: exampleUsageString, overview: "Shark")
let pathArgument = parser.add(positional: ".xcodeproj path", kind: String.self, usage: "The path to the .xcodeproj file")
let outputArgument = parser.add(positional: "output path", kind: String.self, usage: "Path for the output file. Creates a Shark.swift file when this value is a folder")
let nameArgument = parser.add(option: "--name", kind: String.self, usage: #"Top level enum name under which the cases are defined. Defaults to "Shark""#, completion: nil)
let targetArgument = parser.add(option: "--target", kind: String.self, usage: "Target name of the application, useful in case there are multiple application targets", completion: nil)
let localeArgument = parser.add(option: "--locale",kind: String.self,usage:
#"Localization code to use when selecting the Localizable.strings. i.e "en", "de", "es" The "en" locale is used unless specified"#)
let parseResults: ArgumentParser.Result
do {
parseResults = try parser.parse(Array(CommandLine.arguments.dropFirst()))
} catch {
switch error {
case ArgumentParserError.expectedArguments(_, let missingArguments):
print("Missing arguments: \(missingArguments.joined(separator: ", "))")
print("Example usage: \(exampleUsageString)")
case ArgumentParserError.unknownOption(let option):
print("Unknown option: \(option)")
default:
print(error.localizedDescription)
}
exit(EXIT_FAILURE)
}
guard let projectPath = parseResults.get(pathArgument)?.expandingTildeInPath, let outputPath = parseResults.get(outputArgument)?.expandingTildeInPath else {
print("xcodeproj file path and output path parameters are required")
exit(EXIT_FAILURE)
}
guard projectPath.pathExtension == "xcodeproj" else {
print("\(projectPath) should point to a .xcodeproj file")
exit(EXIT_FAILURE)
}
var isDirectory: ObjCBool = false
let outputURL: Foundation.URL
if FileManager.default.fileExists(atPath: outputPath, isDirectory: &isDirectory), isDirectory.boolValue {
outputURL = URL(fileURLWithPath: outputPath).appendingPathComponent("Shark.swift")
} else if outputPath.pathExtension == "swift" {
outputURL = URL(fileURLWithPath: outputPath)
} else {
print("The output path should either point to an existing folder or end with a .swift extension")
exit(2)
}
return Result(projectPath: projectPath,
outputURL: outputURL,
topLevelEnumName: parseResults.get(nameArgument) ?? "Shark",
targetName: parseResults.get(targetArgument),
locale: parseResults.get(localeArgument) ?? "en")
}
}
|
//
// UIImage+Resize.swift
// CoreML in ARKit
//
// Created by Stephanie on 3/12/18.
// Copyright © 2018 CompanyName. All rights reserved.
//
import UIKit
extension UIImage {
func imageWithSize(_ size:CGSize) -> UIImage {
var scaledImageRect = CGRect.zero
let aspectWidth:CGFloat = size.width / self.size.width
let aspectHeight:CGFloat = size.height / self.size.height
let aspectRatio:CGFloat = min(aspectWidth, aspectHeight)
scaledImageRect.size.width = self.size.width * aspectRatio
scaledImageRect.size.height = self.size.height * aspectRatio
scaledImageRect.origin.x = (size.width - scaledImageRect.size.width) / 2.0
scaledImageRect.origin.y = (size.height - scaledImageRect.size.height) / 2.0
UIGraphicsBeginImageContextWithOptions(size, false, 0)
self.draw(in: scaledImageRect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
}
|
//
// AllWorkDidSetScreen.swift
// TodoList
//
// Created by Luong Quang Huy on 2/27/20.
// Copyright © 2020 Luong Quang Huy. All rights reserved.
//
import UIKit
class AllWorkDidSetScreen: UIViewController {
var searchController: UISearchController!
private var currentDataSource: [Awork] = []
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
currentDataSource = dataBase
configureTableView()
configureNavigationBar()
createObserver()
}
func configureTableView(){
tableView.delegate = self
tableView.dataSource = self
tableView.register(WorkDidSetCell.self, forCellReuseIdentifier: "WorkDidSetCell")
}
func configureNavigationBar(){
navigationItem.title = "Tất cả công việc đã tạo"
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
navigationItem.searchController = searchController
searchController.obscuresBackgroundDuringPresentation = false
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
self.navigationController?.navigationBar.barTintColor = UIColor.systemGreen
searchController.hidesNavigationBarDuringPresentation = false
let closeButton = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(closeScreen))
navigationItem.rightBarButtonItem = closeButton
}
@objc func closeScreen(){
navigationController?.dismiss(animated: false, completion: nil)
}
func filterResult(searchTerm: String){
if searchTerm.count > 0{
currentDataSource = dataBase
let searchResult = currentDataSource.filter({$0.content!.replacingOccurrences(of: " ", with: "").lowercased().contains(searchTerm.replacingOccurrences(of: " ", with: "").lowercased())})
currentDataSource = searchResult
tableView.reloadData()
}
}
func resetCurrentDataSource(){
currentDataSource = dataBase
tableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
func createObserver(){
NotificationCenter.default.addObserver(self, selector: #selector(reloadDataTableView(notification:)), name: Notification.Name(rawValue: "deleted Cell"), object: nil)
}
@objc func reloadDataTableView(notification: NSNotification){
if let data = notification.userInfo as? [IndexPath : Int]{
for (indexPath , row) in data{
currentDataSource.remove(at: row)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
}
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension AllWorkDidSetScreen: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return currentDataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "WorkDidSetCell") as! WorkDidSetCell
cell.contentLabel.text = currentDataSource[indexPath.row].content!
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:mm"
cell.dateLabel.text = dateFormatter.string(from: currentDataSource[indexPath.row].date!)
cell.timeLabel.text = timeFormatter.string(from: currentDataSource[indexPath.row].date!)
cell.id = currentDataSource[indexPath.row].workId
cell.navigationDelegate = self.navigationController
cell.indexPath = indexPath
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
UIView.animate(withDuration: 0.01, animations: {
tableView.deselectRow(at: indexPath, animated: true)
})
}
}
extension AllWorkDidSetScreen: UISearchResultsUpdating{
func updateSearchResults(for searchController: UISearchController) {
if let searchText = searchController.searchBar.text{
filterResult(searchTerm: searchText)
}
}
}
extension AllWorkDidSetScreen: UISearchBarDelegate{
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchController.isActive = false
resetCurrentDataSource()
}
}
|
//
// ViewController.swift
// TestingTarget
//
// Created by damouse on 6/1/16.
// Copyright © 2016 I. All rights reserved.
//
import UIKit
import DSON
class Parent: Class {
var name = "Owner"
}
class Cat: Class {
var str: String?
var int: Int?
var bool: Bool?
var float: Float?
var double: Double?
var human = Parent()
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("Testing target started")
let num = NSString(string: "strr")
let dict: [String: AnyObject] = ["str": num, "int": 1, "bool": true, "float": 12.34 as! Float, "double": 56.78 as! Double, "human": ["name": "Neeghbor"]]
let a = try! Cat.from(dict)
print("Done: \(a.str) \(a.int) \(a.bool) \(a.float) \(a.double) \(a.human.name)")
}
}
|
//
// TabBarButton.swift
// MasterDetail
//
// Created by Vladislav Prusakov on 02.09.2019.
// Copyright © 2019 Vladislav Prusakov. All rights reserved.
//
import UIKit
class TabBarButton: UIControl {
private let stackView = UIStackView()
private let imageView = UIImageView()
private let imageContainerView = UIView()
private let badgeView = UIView()
private let badgeLabel = UILabel()
var axis: NSLayoutConstraint.Axis {
get { return self.stackView.axis }
set { self.stackView.axis = newValue }
}
override var isSelected: Bool {
didSet {
self.updateTintColor()
}
}
override func tintColorDidChange() {
super.tintColorDidChange()
self.updateTintColor()
}
weak var tabBarItem: UITabBarItem?
private var itemTintColor: UIColor
private var itemUnselectedTintColor: UIColor
init(item: UITabBarItem, tabBar: SideTabBar, target: Any, action: Selector) {
itemTintColor = tabBar.tintColor
itemUnselectedTintColor = tabBar.unselectedItemTintColor ?? UIColor(white: 0.57, alpha: 1)
super.init(frame: .zero)
self.setup()
self.addTarget(target, action: action, for: .touchUpInside)
let image = item.image ?? item.selectedImage
self.imageView.image = image?.withRenderingMode(.alwaysTemplate).withAlignmentRectInsets(item.imageInsets)
self.tabBarItem = item
}
private func setup() {
self.updateTintColor()
stackView.translatesAutoresizingMaskIntoConstraints = false
imageView.translatesAutoresizingMaskIntoConstraints = false
imageContainerView.translatesAutoresizingMaskIntoConstraints = false
imageContainerView.addSubview(imageView)
imageContainerView.isUserInteractionEnabled = false
imageView.contentMode = .scaleAspectFit
imageView.isUserInteractionEnabled = false
stackView.isUserInteractionEnabled = false
NSLayoutConstraint.activate([
imageView.centerXAnchor.constraint(equalTo: imageContainerView.centerXAnchor),
imageView.centerYAnchor.constraint(equalTo: imageContainerView.centerYAnchor),
imageView.widthAnchor.constraint(equalToConstant: 28),
imageView.heightAnchor.constraint(equalToConstant: 28),
])
self.addSubview(stackView)
stackView.addArrangedSubview(imageContainerView)
NSLayoutConstraint.activate([
stackView.leftAnchor.constraint(equalTo: self.leftAnchor),
stackView.rightAnchor.constraint(equalTo: self.rightAnchor),
stackView.topAnchor.constraint(equalTo: self.topAnchor),
stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
imageContainerView.heightAnchor.constraint(equalTo: stackView.widthAnchor, multiplier: 1)
])
}
private func updateTintColor() {
if isSelected {
self.imageView.tintColor = itemTintColor
} else {
self.imageView.tintColor = itemUnselectedTintColor
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// Created by Ceri-anne Jackson on 23/07/2020.
// Copyright © 2020 Ceri-anne Jackson. All rights reserved.
//
import UIKit
class InitialViewController: UIViewController {
@IBAction func chooseHouseTapped(_ sender: Any) {
fetchHouse()
}
@IBAction func viewCharacterTapped(_ sender: Any) {
fetchCharacters()
}
@IBAction func viewSpellsTapped(_ sender: Any) {
fetchSpells()
}
private func fetchCharacters() {
Networking().fetchCharacters() { characters in
self.loadCharactersViewController(with: characters)
}
}
private func fetchHouse() {
Networking().fetchHouse() { house in
self.loadHouseViewController(with: house)
}
}
private func fetchSpells() {
Networking().fetchSpells() { spells in
self.loadSpellsViewController(with: spells)
}
}
private func loadHouseViewController(with house: House) {
DispatchQueue.main.async {
guard let viewController = UIStoryboard(name: "House", bundle: self.nibBundle).instantiateInitialViewController() as? HouseViewController else {
return
}
viewController.house = house
self.navigationController?.pushViewController(viewController , animated: true)
}
}
private func loadCharactersViewController(with characters: [Character]) {
DispatchQueue.main.async {
guard let viewController = UIStoryboard(name: "Characters", bundle: self.nibBundle).instantiateInitialViewController() as? CharactersViewController else {
return
}
viewController.characters = characters
self.navigationController?.pushViewController(viewController , animated: true)
}
}
private func loadSpellsViewController(with spells: [Spell]) {
DispatchQueue.main.async {
guard let viewController = UIStoryboard(name: "Spells", bundle: self.nibBundle).instantiateInitialViewController() as? SpellsViewController else {
return
}
viewController.spells = spells
self.navigationController?.pushViewController(viewController , animated: true)
}
}
}
|
import UIKit
class LiveTableViewController: BaseLiveTableViewController {
override func selectScene(_ scene: CGSSLiveScene) {
super.selectScene(scene)
let vc = BeatmapViewController()
vc.setup(with: scene)
vc.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
}
}
|
//
// Organization+CoreDataProperties.swift
// GiftManager
//
// Created by David Johnson on 9/4/17.
// Copyright © 2017 David Johnson. All rights reserved.
//
import Foundation
import CoreData
extension Organization {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Organization> {
return NSFetchRequest<Organization>(entityName: "Organization")
}
@NSManaged public var name: String?
@NSManaged public var phone: String?
@NSManaged public var persons: Set<Person>?
}
// MARK: Generated accessors for persons
extension Organization {
@objc(addPersonsObject:)
@NSManaged public func addToPersons(_ value: Person)
@objc(removePersonsObject:)
@NSManaged public func removeFromPersons(_ value: Person)
@objc(addPersons:)
@NSManaged public func addToPersons(_ values: NSSet)
@objc(removePersons:)
@NSManaged public func removeFromPersons(_ values: NSSet)
}
|
//
// URL+Convenience.swift
//
//
// Created by Vladislav Fitc on 18/11/2021.
//
import Foundation
extension URL {
static var indexesV1 = Self(string: "/1/indexes")!
static var settings = Self(string: "/settings")!
static var clustersV1 = Self(string: "/1/clusters")!
static var synonyms = Self(string: "/synonyms")!
static var eventsV1 = Self(string: "/1/events")!
static var ABTestsV2 = Self(string: "/2/abtests")!
static var keysV1 = Self(string: "/1/keys")!
static var logs = Self(string: "/1/logs")!
static var strategies = Self(string: "/1/strategies")!
static var places = Self(string: "/1/places")!
static var answers = Self(string: "/1/answers")!
static var dictionaries = Self(string: "/1/dictionaries")!
static var task = Self(string: "/1/task")!
func appending<R: RawRepresentable>(_ rawRepresentable: R) -> Self where R.RawValue == String {
return appendingPathComponent(rawRepresentable.rawValue.addingPercentEncoding(withAllowedCharacters: .urlPathComponentAllowed)!, isDirectory: false)
}
func appending(_ pathComponent: PathComponent) -> Self {
return appendingPathComponent(pathComponent.rawValue.addingPercentEncoding(withAllowedCharacters: .urlPathComponentAllowed)!, isDirectory: false)
}
enum PathComponent: String {
case search
case stop
case clear
case restore
case reverse
case browse
case deleteByQuery
case batch
case partial
case mapping
case pending
case top
case task
case query
case prediction
case operation
case languages
case keys
case queries
case objects
case personalization
case recommendations
case rules
case facets
case synonyms
case settings
case asterisk = "*"
}
}
|
//
// NewDataEntryTableViewController.swift
// transinfoFinal
//
// Created by Jessica Cotrina Revilla on 7/31/16.
// Copyright © 2016 Universidad de puerto rico-Mayaguez. All rights reserved.
//
import UIKit
class NewDataEntryTableViewController: UITableViewController {
override func viewDidLoad() {
}
}
|
//
// Response.swift
// FMDBManager
//
// Created by 张旭 on 16/1/23.
// Copyright © 2016年 张旭. All rights reserved.
//
import Foundation
import Alamofire
struct Response{
/**
获取网络html数据(回调方式)
GET方式
- parameter url: 网络链接
- parameter parameters: 参数
- parameter headers: http头
- parameter completionHandler: 回调函数
*/
static func getHtml(url:String,parameters:[String: AnyObject]? = nil,headers: [String: String]? = nil,completionHandler:(NSString?)->Void){
getJson(url, parameters: parameters, headers: headers) { (data, error) -> Void in
if let htmlData = data{
let string = NSString(data: htmlData, encoding: NSUTF8StringEncoding)
completionHandler(string)
}else{
completionHandler("")
}
}
}
/**
获取网络json数据(回调方式)
GET方式
- parameter url: 网络链接
- parameter parameters: 参数
- parameter headers: http头
- parameter completionHandler: 回调函数
*/
static func getJson(url:String,parameters:[String: AnyObject]? = nil,headers: [String: String]? = nil,completionHandler:(NSData?,NSError?)->Void){
getJson(Alamofire.Method.GET, url: url, parameters: parameters, headers: headers) { (data, error) -> Void in
completionHandler(data, error)
}
}
/**
获取网络json数据
GET方式
- parameter url: 网络链接
- parameter parameters: 参数
- parameter headers: http头
- returns: 返回Request
*/
static func getJson(url:String,parameters:[String: AnyObject]? = nil,headers: [String: String]? = nil)->Request?{
return getJson(.GET, url: url, parameters: parameters, headers: headers)
}
private static func getJson(method: Alamofire.Method,url:String,parameters:[String: AnyObject]? = nil,encoding:ParameterEncoding = .URL,headers: [String: String]? = nil)->Request?{
return Alamofire.request(method, url, parameters: parameters, encoding: encoding, headers: headers)
.validate(statusCode: 200..<300)
.responseJSON { response in}
}
private static func getJson(method: Alamofire.Method,url:String,parameters:[String: AnyObject]? = nil,encoding:ParameterEncoding = .URL,headers: [String: String]? = nil,completionHandler:(NSData?,NSError?)->Void){
Alamofire.request(method, url, parameters: parameters, encoding: encoding, headers: headers)
.validate(statusCode: 200..<300)
.responseJSON { response in
completionHandler(response.data,response.result.error)}
}
}
//MARK:获取url中的参数
extension Response{
/**
获取url中的参数
- parameter url: 连接
- returns: 返回字典
*/
static func getUrlParameter(url:String?)-> [String:String]?{
guard url != nil else {return nil}
var parameterDic = [String:String]()
let urls = url!.characters.split("?")
guard urls.count > 1 else {return nil}
let parameters = urls[1].split("&")
for parameter in parameters{
guard parameter.first != "=" else {continue}
let par = parameter.split("=")
let name = par[0].map {switchChar($0)}.joinWithSeparator("")
let value = (par.count > 1) ? par[1].map {switchChar($0)}.joinWithSeparator("") : ""
guard !name.isEmpty else {continue}
parameterDic[name] = value
}
return parameterDic
}
private static func switchChar(char:Character)-> String{
var str = ""
str.append(char)
return str
}
} |
//
// HamburgerCell.swift
// AarambhPlus
//
// Created by Santosh Kumar Sahoo on 9/7/18.
// Copyright © 2018 Santosh Dev. All rights reserved.
//
import UIKit
class HamburgerProfileCell: UITableViewCell {
@IBOutlet weak private var nameLabel: UILabel!
@IBOutlet weak private var profilePicImageView: UIImageView!
override func prepareForReuse() {
super.prepareForReuse()
}
func updateUI() {
if UserManager.shared.isLoggedIn {
nameLabel.text = UserManager.shared.user?.displayName
profilePicImageView.setKfImage(UserManager.shared.user?.profilePic)
//Circle the profile Image
profilePicImageView?.layer.cornerRadius = (profilePicImageView?.frame.size.width ?? 0.0) / 2
profilePicImageView?.clipsToBounds = true
profilePicImageView?.layer.borderWidth = 3.0
profilePicImageView?.layer.borderColor = UIColor.white.cgColor
} else {
nameLabel.text = "Click here to login."
//Circle the profile Image
profilePicImageView?.layer.cornerRadius = (profilePicImageView?.frame.size.width ?? 0.0) / 2
profilePicImageView?.clipsToBounds = true
profilePicImageView?.layer.borderWidth = 3.0
profilePicImageView?.layer.borderColor = UIColor.white.cgColor
}
}
}
class HamburgerItemCell: UITableViewCell {
@IBOutlet weak var titleImg: UIImageView!
@IBOutlet weak private var titleLabel: UILabel!
func updateUI(title: String?) {
titleLabel.text = title
}
func updateUI(imgge: UIImage?) {
titleImg.image = imgge
}
}
|
//
// GameScene.swift
// OneSecond
//
// Created by William Yang on 12/9/17.
// Copyright © 2017 S(h)itty Games. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
let redButton: SKSpriteNode = SKSpriteNode(imageNamed: "RedButton")
let restartButton: SKSpriteNode = SKSpriteNode(imageNamed: "RedButton")
let timerLabel: SKLabelNode = SKLabelNode(fontNamed: "Menlo")
let pressTheButtonLabel: SKLabelNode = SKLabelNode(fontNamed: "Menlo")
let totalScoreLabel: SKLabelNode = SKLabelNode(fontNamed: "Menlo")
// Time Stuff
var startTime = TimeInterval()
let originalTime: CGFloat = 0.0
lazy var timeLeft: CGFloat = self.originalTime
// Adding more time stuff
var seconds: TimeInterval = 0.0
var totalScore: CGFloat = 0
var timer = Timer()
var stringTimer = ""
var isTimeRunning = false
override func didMove(to view: SKView) {
setupAllNodes()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first{
let touchedLocation = touch.location(in: self)
let touchedNode = self.atPoint(touchedLocation)
if touchedNode.name == "RedButton" {
print("Red Button has been touched")
if isTimeRunning == false {
runTimer()
} else {
restartTimer()
}
if seconds > 1.01 {
print("Too late!!: \(seconds)")
} else if(seconds > 0.999 && seconds < 1.001) {
print("RIGHT ON!!: \(seconds)")
} else if seconds < 0.99 {
print("Too early: \(seconds)")
}
if timeLeft > 1.0 {
totalScore += 1
}
}
if touchedNode.name == "RestartButton" {
print("Restart Button has been touched")
restartTimer()
}
}
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
// updateTextLabel(labelNode: timerLabel, updateText: "Time: \(timeLeft)")
updateTextLabel(labelNode: timerLabel, updateText: "Time: \(stringTimer)")
updateTextLabel(labelNode: totalScoreLabel, updateText: "Total score: \(totalScore)")
}
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
startTime = Date.timeIntervalSinceReferenceDate
isTimeRunning = true
}
func restartTimer() {
timer.invalidate()
isTimeRunning = false
timeLeft = originalTime
}
func updateTextLabel(labelNode _labelNode: SKLabelNode, updateText _updateText: String){
_labelNode.text = _updateText
}
@objc func updateTimer(){
let currentTime = Date.timeIntervalSinceReferenceDate
//print("Current Time: " + String(currentTime))
//Find the difference between current time and start time.
var elapsedTime: TimeInterval = currentTime - startTime
// print("ELasped Time: " + String(elapsedTime))
//calculate the seconds in elapsed time.
seconds = elapsedTime
elapsedTime -= TimeInterval(seconds)
// print("Seconds: " + String(seconds))
//find out the fraction of milliseconds to be displayed.
//let fraction = (elapsedTime * 100)
//print("Fraction: " + String(fraction))
//add the leading zero for minutes, seconds and millseconds and store them as string constants
let strSeconds = String(format: "%.02f", seconds)
// let strFraction = String(format: "%02d", fraction)
// let strFraction = String(format: "%.02f", fraction)
stringTimer = strSeconds
//print("StrSeconds: " + strSeconds)
// print("StrFraction: " + strFraction)
//concatenate minuets, seconds and milliseconds as assign it to the UILabel
// print("\(strSeconds):\(strFraction)")
timerLabel.text = "\(strSeconds)"
}
func setupAllNodes() {
setupSpriteNode(spriteNode: redButton, position: CGPoint(x: self.size.width / 2, y: self.size.height / 2), anchorPoint: CGPoint(x: 0.5, y: 0.5), zPosition : 10, scale: 0.5, name : "RedButton")
setupSpriteNode(spriteNode: restartButton, position: CGPoint(x: self.size.width * 0.75, y: self.size.height * 0.85), anchorPoint: CGPoint(x: 0.5, y: 0.5), zPosition: 10, scale: 0.10, name: "RestartButton")
setupLabelNode(labelNode: timerLabel, text: "Time: \(timeLeft)", fontColor: SKColor.white, fontSize: 75, zPosition: 10, horizontalAlignmentMode: .center, verticalAlignmentMode: .center, position: CGPoint(x: self.size.width * 0.25, y: self.size.height * 0.25))
setupLabelNode(labelNode: pressTheButtonLabel, text: "Press the Button", fontColor: SKColor.white, fontSize: 75, zPosition: 10, horizontalAlignmentMode: .center, verticalAlignmentMode: .center, position: CGPoint(x: self.size.width / 2, y: self.size.height * 0.75))
setupLabelNode(labelNode: totalScoreLabel, text: "Total Score: \(totalScore)", fontColor: SKColor.white, fontSize: 75, zPosition: 10, horizontalAlignmentMode: .center, verticalAlignmentMode: .center, position: CGPoint(x: self.size.width / 2, y: self.size.height * 0.10))
}
func setupSpriteNode(spriteNode _spriteNode: SKSpriteNode, position _position: CGPoint, anchorPoint _anchorPoint: CGPoint, zPosition _zPosition: CGFloat, scale _scale: CGFloat, name _name: String) {
_spriteNode.position = _position
_spriteNode.anchorPoint = _anchorPoint
_spriteNode.zPosition = _zPosition
_spriteNode.setScale(_scale)
_spriteNode.name = _name
addChild(_spriteNode)
}
func setupLabelNode(labelNode _labelNode: SKLabelNode, text _text: String, fontColor _fontColor: SKColor, fontSize _fontSize: CGFloat, zPosition _zPosition: CGFloat, horizontalAlignmentMode _horizontalAlignmentMode: SKLabelHorizontalAlignmentMode, verticalAlignmentMode _verticalAlignmentMode: SKLabelVerticalAlignmentMode, position _position: CGPoint) {
_labelNode.text = _text
_labelNode.fontColor = _fontColor
_labelNode.fontSize = _fontSize
_labelNode.zPosition = _zPosition
_labelNode.horizontalAlignmentMode = _horizontalAlignmentMode
_labelNode.verticalAlignmentMode = _verticalAlignmentMode
_labelNode.position = _position
addChild(_labelNode)
}
}
|
//
// GeometryReader_1.swift
// LearningSwiftUI
//
// Created by Metin HALILOGLU on 5/2/21.
//
import SwiftUI
struct GeometryReader_1: View {
var body: some View {
VStack(spacing: 20){
Text("Geometry Reader Örnek -1 ").font(.largeTitle)
Text("Giriş").font(.title).foregroundColor(.gray)
Text("Geometry Reader Push-Out türünde bir container view. Bu yüzden yerleştiği tüm boşluğu kaplamaya çalışır. Onu kullanarak barındırdığı viewleri konumlandırabiliriz.").font(.title).padding().layoutPriority(1)
GeometryReader { _ in
Text("Viewler Geometry Reader içinde merkeze konumlandırılır").font(.title)
}.foregroundColor(.white).background(Color.blue)
}
}
}
struct GeometryReader_1_Previews: PreviewProvider {
static var previews: some View {
GeometryReader_1()
}
}
|
//
// FavoriteLeaguesViewController.swift
// SportsApp
//
// Created by ahmedpro on 4/25/20.
// Copyright © 2020 Reham Ezzat. All rights reserved.
//
import UIKit
class FavoriteLeaguesViewController: UIViewController, FavoriteLeaguesViewProtocol {
@IBOutlet weak var noFavoriteLeaguesLabel: UILabel!
private var favoriteLeaguesPresenter: FavoriteLeaguesPresenterProtocol?
private var tableView: UITableView?
private var sportLeagues = Array<SportLeague>()
override func viewDidLoad() {
super.viewDidLoad()
title = "Favorite Leagues"
let appDelegate = UIApplication.shared.delegate as! AppDelegate
favoriteLeaguesPresenter = FavoriteLeaguesPresenter(favoriteLeaguesView: self, appDelegate: appDelegate)
if let tb = Bundle.main.loadNibNamed("SportLeaguesTableView", owner: self, options: nil)?.first as? SportLeaguesTableView {
tableView = tb
tableView?.delegate = self
tableView?.dataSource = self
tableView?.isHidden = true
view.addSubview(tableView!)
}
}
func updateTableView(retrievedSportLeagues: [SportLeague]) {
if retrievedSportLeagues.count > 0 {
noFavoriteLeaguesLabel.isHidden = true
tableView?.isHidden = false
sportLeagues = retrievedSportLeagues
tableView!.reloadData()
} else {
tableView?.isHidden = true
noFavoriteLeaguesLabel.isHidden = false
}
}
override func viewDidAppear(_ animated: Bool) {
favoriteLeaguesPresenter?.loadSportLeagues()
}
}
extension FavoriteLeaguesViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sportLeagues.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let sportLeague = sportLeagues[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "sportLeaguesCell") as! SportLeaguesTableCell
cell.sportLeagueImageView.kf.setImage(with: URL(string: sportLeague.leagueImageURL ?? ""))
cell.sportLeagueImageView.kf.indicatorType = .activity
cell.sportLeagueLabel.text = sportLeague.leagueName ?? ""
cell.youtubeButton.tag = indexPath.item
cell.youtubeButton.addTarget(self, action: #selector(goToYoutube(_:)), for: .touchUpInside)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100.0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let leagueDetailsStoryBoard = UIStoryboard(name: "Reham", bundle: nil)
let leagueDetailsView = leagueDetailsStoryBoard.instantiateViewController(withIdentifier: "LDVC") as! LeagueDetailsViewController
leagueDetailsView.sportLeague = sportLeagues[indexPath.item]
present(leagueDetailsView, animated: true, completion: nil)
}
@objc private func goToYoutube(_ sender: UIButton) {
let s = sportLeagues[sender.tag].leagueYoutubeURL ?? ""
if !s.isEmpty {
let url = URL(string: "https://\(s)")!
if !UIApplication.shared.canOpenURL(url) {
}
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
let alertView = UIAlertController(title: "YOUTUBE", message: "Sorry! there is no youtube's channel availabel yet.", preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
navigationController?.present(alertView, animated: true, completion: nil)
}
}
}
|
import XCTest
import SwiftCheck
import BowLaws
import Bow
public final class ForStream {}
public final class StreamFPartial<A>: Kind<ForStream, A> {}
public typealias StreamFOf<A, S> = Kind<StreamFPartial<A>, S>
public final class StreamF<A, S>: StreamFOf<A, S> {
internal init(s: S, next: @escaping (S) -> (S, A)) {
self.s = s
self.next = next
}
let s: S
let next: (S) -> (S, A)
static func fix(_ fa: StreamFOf<A, S>) -> StreamF<A, S> {
fa as! StreamF<A, S>
}
}
public postfix func ^<A, S>(_ fa: StreamFOf<A, S>) -> StreamF<A, S> {
StreamF.fix(fa)
}
typealias Stream<A> = Exists<StreamFPartial<A>>
let nats: Stream<String> = Stream(
StreamF<String, Int>(s: 0, next: { (n: Int) -> (Int, String) in
(n+1, "\(n)")
})
)
class HeadF<A>: CokleisliK<StreamFPartial<A>, A> {
override init() {
super.init()
}
override func invoke<T>(_ fa: Kind<StreamFPartial<A>, T>) -> A {
let s = StreamF.fix(fa).s
let next = StreamF.fix(fa).next
return next(s).1
}
}
func head<R>(_ s: Stream<R>) -> R {
s.run(HeadF())
}
class EnumerateF<A>: CokleisliK<StreamFPartial<A>, [A]> {
init(n: Int) {
self.n = n
super.init()
}
let n: Int
override func invoke<S>(_ fa: Kind<StreamFPartial<A>, S>) -> [A] {
typealias P = (s: S, aa: [A])
let initialState = fa^.s
let next: State<P, A> = State<S, A>(fa^.next)
.focus({ $0.0 }, { ($1, $0.1) })
let f: State<P, Void> = StatePartial<P>.tailRecM(n) { (i: Int) -> State<P, Either<Int, Void>> in
let r = State<P, A>.var()
return binding(
r <-- next,
|<-StatePartial<P>.modify { oldState in
(oldState.s, oldState.aa + [r.get])
},
yield: (i == 1) ? Either.right(()) : Either.left(i-1))^
}^
return f.runS((initialState, [])).1
}
}
func enumerate<R>(_ s: Stream<R>, n: Int) -> [R] {
s.run(EnumerateF(n: n))
}
class ExistsTests: XCTestCase {
func testImplementationOfDataTypeBasedOnExists() {
XCTAssertEqual(head(nats), "0")
XCTAssertEqual(enumerate(nats, n: 4), ["0", "1", "2", "3"])
}
/// Given a function `f: Kind<F, A> -> R` polymorphic on `A`,
/// assert that wrapping a value `fa: Kind<F, A>` in an `Exists<F>`
/// does not change the result of `f`, i.e `f(fa) == Exists(fa).run(f)`.
func testFunctionApplicationTransparency() {
property("Function application transparency") <~ forAll { (fa: ArrayK<Int>) in
Exists(fa).run(F()) == F()(fa)
}
}
func testCustomStringConvertibleLaws() {
CustomStringConvertibleLaws<Exists<ForArrayK>>.check()
CustomStringConvertibleLaws<Exists<ForId>>.check()
CustomStringConvertibleLaws<Exists<ForOption>>.check()
}
func testDescriptionMatchesInnerTypeDescription() {
property("""
Description matches inner type's description
when the inner type conforms to CustomStringConvertible
""") <~ forAll { (array: ArrayK<Int>) in
Exists(array).description == array.description
}
}
func testDescriptionDefaultsToStringInterpolation() {
property("""
Description defaults to string interpolation
when the inner type does not conform to CustomStringConvertible
""") <~ forAll { (array: ArrayK<Function0<Int>>) in
return Exists(array).description == "\(array)"
}
}
func testCustomDebugStringConvertibleWhenInnerTypeIs() {
property("""
Description matches inner type's description
when the inner type conforms to CustomStringConvertible
""") <~ forAll { (array: ArrayK<String>) in
return Exists(array).debugDescription == array.debugDescription
}
}
func testDebugDescriptionDefaultsToStringInterpolation() {
property("""
Description defaults to string interpolation
when the inner type does not conform to CustomStringConvertible
""") <~ forAll { (array: ArrayK<Function0<Int>>) in
return Exists(array).debugDescription == "\(array)"
}
}
class F: CokleisliK<ArrayKPartial, Int64> {
override func invoke<A>(_ fa: ArrayKOf<A>) -> Int64 {
fa^.count
}
}
}
|
//
// Product.swift
// Cobera
//
// Created by Emilio Del Castillo on 01/04/2021.
//
import Foundation
class Product: NSObject, NSCoding {
enum CapacityUnit: String, CaseIterable {
case mililitre = "ml"
case centilitre = "cl"
case litre = "l"
case gram = "g"
case kilo = "kg"
}
var identifier: String
var brand: String
var name: String
var capacity: Int
var capacityUnit: CapacityUnit
/**
Retruns a dictionary with all the variables of the instance.
*/
var dictionary: [String: Any] {
return ["name": name,
"brand": brand,
"capacity": capacity,
"capacityUnit": capacityUnit.rawValue]
}
func encode(with coder: NSCoder) {
coder.encode(identifier, forKey: "identifier")
coder.encode(brand, forKey: "brand")
coder.encode(name, forKey: "name")
coder.encode(capacity, forKey: "capacity")
coder.encode(capacityUnit.rawValue, forKey: "capacityUnit")
}
required convenience init?(coder: NSCoder) {
let identifier = coder.decodeObject(forKey: "identifier") as! String
let brand = coder.decodeObject(forKey: "brand") as! String
let name = coder.decodeObject(forKey: "name") as! String
let capacity = coder.decodeInteger(forKey: "capacity")
let capacityUnit = CapacityUnit(rawValue: coder.decodeObject(forKey: "capacityUnit") as! String)!
self.init(identifier: identifier, brand: brand, name: name, capacity: capacity, capacityUnit: capacityUnit)
}
init(identifier: String, brand: String, name: String, capacity: Int, capacityUnit: CapacityUnit) {
self.identifier = identifier
self.brand = brand
self.name = name
self.capacity = capacity
self.capacityUnit = capacityUnit
}
/**
Returns a hopefully unique identifier for a product without barcode.
- Parameters:
- brand: The product brand
- name: The product name
- capacity: The product capacity
- capacityUnit: The unit (e.g., ml)
When a product is added manually, no barcode is provided. This function should help to identify it.
*/
class func getUniqueIdentifier(brand: String, name: String, capacity: Int, capacityUnit: CapacityUnit) -> String {
return brand + name + capacity.description + capacityUnit.rawValue
}
}
|
//
// PlatformListVC.swift
// iVPN-Mac
//
// Created by Steven on 15/11/5.
// Copyright © 2015年 Neva. All rights reserved.
//
import Cocoa
class PlatformListVC: NSViewController, NSOutlineViewDataSource, NSOutlineViewDelegate {
@IBOutlet weak var outlineView: NSOutlineView!
let dataItems = ["Tianxing(天行)", "VPN Gate"]
override func viewDidLoad() {
super.viewDidLoad()
}
func outlineView(outlineView: NSOutlineView, viewForTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> NSView? {
let cell = outlineView.makeViewWithIdentifier("DataCell", owner: self) as! NSTableCellView
let info = item as? String
cell.textField?.stringValue = info ?? "-"
return cell
}
func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool {
return false
}
func outlineView(outlineView: NSOutlineView, isGroupItem item: AnyObject) -> Bool {
return false
}
func outlineView(outlineView: NSOutlineView, shouldSelectItem item: AnyObject) -> Bool {
return true
}
func outlineViewSelectionDidChange(notification: NSNotification) {
// TODO
}
func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject {
return dataItems[index]
}
func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int {
// The root item has each collection as its children.
if item == nil {
return 0
return dataItems.count
} else {
return 0
}
}
} |
//
// ViewController.swift
// Task Sorter Mac
//
// Created by Beau Young on 17/11/2015.
// Copyright © 2015 Beau Young. All rights reserved.
//
import Cocoa
class TasksViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
|
//
// BooleanToStringTests.swift
// BooleanToStringTests
//
// Created by Lucas Lima Noronha on 21/06/2019.
// Copyright © 2019 Lucas Lima Noronha. All rights reserved.
//
import XCTest
@testable import BooleanToString
class BooleanToStringTests: XCTestCase {
static var allTests = [
("Function should return \"true\" when true is passed as input.", testExample1),
("Function should return \"false\" when false is passed as input.", testExample2)
]
func testExample1() {
XCTAssertEqual(booleanToString(true), "true")
}
func testExample2() {
XCTAssertEqual(booleanToString(false), "false")
}
func booleanToString(_ b: Bool) -> String {
return b.description
}
}
|
//
// TBCView.swift
// Radio
//
// Created by Mac on 2020/12/22.
//
import SwiftUI
struct TBCView: View {
var body: some View {
TabView{
//MARK: - Tab 1
CenterView()
.navigationViewStyle(StackNavigationViewStyle())
.tabItem {
Image(systemName: "antenna.radiowaves.left.and.right")
Text("中央")
}
ProvinceView()
.navigationViewStyle(StackNavigationViewStyle())
.tabItem {
Image(systemName: "map.fill")
Text("省市")
}
NetView()
.navigationViewStyle(StackNavigationViewStyle())
.tabItem {
Image(systemName: "chart.bar.doc.horizontal.fill")
Text("网络")
}
}
}
}
struct TBCView_Previews: PreviewProvider {
static var previews: some View {
TBCView()
}
}
|
// SPDX-License-Identifier: MIT
// Copyright © 2018-2019 WireGuard LLC. All Rights Reserved.
import UIKit
class LoaderController: NSObject {
static let sharedInstance = LoaderController()
private let activityIndicator = UIActivityIndicatorView()
//MARK: - Private Methods -
private func setupLoader() {
removeLoader()
activityIndicator.hidesWhenStopped = true
activityIndicator.style = .gray
activityIndicator.color = .black
//activityIndicator.backgroundColor = UIColor(hexString: "##E9EFF0").withAlphaComponent(0.10)
}
//MARK: - Public Methods -
func showLoader(view : UIView) {
let appDel = UIApplication.shared.delegate as! AppDelegate
let holdingView = appDel.window!.rootViewController!.view!
DispatchQueue.main.async {
self.activityIndicator.center = holdingView.center
self.activityIndicator.startAnimating()
holdingView.addSubview(self.activityIndicator)
UIApplication.shared.beginIgnoringInteractionEvents()
}
}
func removeLoader(){
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
self.activityIndicator.removeFromSuperview()
UIApplication.shared.endIgnoringInteractionEvents()
}
}
}
|
//
// URLWithTitle.swift
// HSAPP-iOS
//
// Created by Tony Cioara on 6/13/18.
// Copyright © 2018 Tony Cioara. All rights reserved.
//
import Foundation
struct URLWithTitle {
var URL: URL
var title: String
init (URL: URL, title: String) {
self.URL = URL
self.title = title
}
}
|
//
// Concentration.swift
// Concentration-Assignment1
//
// Created by Shakaib Akhtar on 19/08/2019.
// Copyright © 2019 iParagons. All rights reserved.
//
import Foundation
class Concentration {
var cards = [Card]()
var flipCount:Int
var oneFaceUpOnlyIndex: Int?
func flipCardInModel(at index: Int) {
flipCount += 1
// things to check before flipping the card
//if there is already one faceup card so check if the new tapped card is a different card then proceed
if let matchIndex = oneFaceUpOnlyIndex, matchIndex != index {
//if both the faceUpCards match then mark them as matched
if cards[matchIndex].cardNumber == cards[index].cardNumber {
cards[matchIndex].isMatched = true
cards[index].isMatched = true
}
// check the flag, all cards are face down now
oneFaceUpOnlyIndex = nil
}
else { // if there is no faceUp card
// flip all cards as face down
for cardIndex in 0..<cards.count {
cards[cardIndex].isFaceUp = false
}
// select the oneFaceUpCardOnly index
oneFaceUpOnlyIndex = index
}
// flip the card, and
//mark that it is atleast flipped once(for score purpose)
cards[index].isFaceUp = !cards[index].isFaceUp
cards[index].isSeen = true
}
init(noOfPairs: Int) {
flipCount = 0
// create the pairs of cards
for _ in 1...noOfPairs {
let card = Card()
cards += [card,card]
}
// shuffling cards logic
var swapFrom = 0
var swapTo = 0
for _ in 0..<cards.count {
repeat {
// pick 2 random indices from array and swap them
swapFrom = cards.count.arc4random()
swapTo = cards.count.arc4random()
} while(swapFrom == swapTo)
cards.swapAt(swapFrom, swapTo)
}
}
}
|
//
// SBNavigationController.swift
// Parkings
//
// Created by ALEXEY ABDULIN on 17/07/2019.
// Copyright © 2019 ALEXEY ABDULIN. All rights reserved.
//
import UIKit
open class SBNavigationController: UINavigationController, UINavigationControllerDelegate, SBMVVMHolderProtocol
{
@objc
open var showRootBack = true;
override open func viewDidLoad()
{
super.viewDidLoad();
delegate = self
}
//MARK: - MVVM
public func BindVM( vm: SBViewModel )
{
(viewControllers.first as? SBMVVMHolderProtocol)?.BindVM( vm: vm );
}
//MARK: - ACTIONS
@objc func Back()
{
if viewControllers.count == 1
{
dismiss( animated: true, completion: nil );
}
else
{
popViewController( animated: true );
}
}
//MARK: - UINavigationControllerDelegate
open func navigationController( _ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool )
{
if (viewControllers.count == 1) && !showRootBack
{
}
else
{
let backItem = UIBarButtonItem( image: UIImage( named: "IconBack"), style: .plain, target: self, action: #selector( Back ) );
viewController.navigationItem.leftBarButtonItem = backItem;
}
}
}
|
//
// AddingTokenViewController.swift
// XDCExample
//
// Created by Developer on 13/08/21.
//
import UIKit
class AddingTokenViewController: UIViewController {
var tokenAddrr = ""
var tokenSym = ""
var tokenDeci = ""
var accAddr = ""
var privateK = ""
@IBOutlet var tokenAddress: UITextField!
@IBOutlet var tokenSymbol: UITextField!
@IBOutlet var tokenDecimal: UITextField!
@IBOutlet var addToken: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setupHideKeyboardOnTap()
addToken.layer.cornerRadius = 7
// Do any additional setup after loading the view.
}
@IBAction func AddTokenBtn(_ sender: UIButton) {
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let nextVc = storyboard.instantiateViewController(withIdentifier: "AddedTokenViewController") as! AddedTokenViewController
nextVc.tokenAddrr = tokenAddress.text!
nextVc.tokenSym = tokenSymbol.text!
nextVc.tokenDeci = tokenDecimal.text!
nextVc.accAddr = self.accAddr
nextVc.privateK = self.privateK
navigationController?.pushViewController(nextVc, animated: 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.
}
*/
@IBAction func bckBtn(_ sender: UIButton) {
navigationController?.popViewController(animated: true)
}
}
|
//
// TextViewVC.swift
// UIinDeep
//
// Created by eduardo fulgencio on 17/08/2019.
// Copyright © 2019 Eduardo Fulgencio Comendeiro. All rights reserved.
//
import UIKit
class TextViewVC: UIViewController {
var textView: UITextView!
var textStorage: SyntaxHighlightTextStorage!
override func viewDidLoad() {
super.viewDidLoad()
createTextView()
}
func createTextView() {
// 1
let attrs = [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .body)]
let attrString = NSAttributedString(string: "note.contents", attributes: attrs)
textStorage = SyntaxHighlightTextStorage()
textStorage.append(attrString)
let newTextViewRect = view.bounds
// 2
let layoutManager = NSLayoutManager()
// 3
let containerSize = CGSize(width: newTextViewRect.width,
height: .greatestFiniteMagnitude)
let container = NSTextContainer(size: containerSize)
container.widthTracksTextView = true
layoutManager.addTextContainer(container)
textStorage.addLayoutManager(layoutManager)
// 4
textView = UITextView(frame: newTextViewRect, textContainer: container)
textView.delegate = self
view.addSubview(textView)
// 5
textView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
textView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
textView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
textView.topAnchor.constraint(equalTo: view.topAnchor),
textView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
/*
// 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.
}
*/
}
extension TextViewVC : UITextViewDelegate {
}
|
//
// ViewController.swift
// Cotação Moeda
//
// Created by André Brilho on 19/12/16.
// Copyright © 2016 Andre Brilho. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var lblValorDefault: UILabel!
@IBOutlet weak var txtvalor: UITextField!
@IBOutlet weak var lblValorCalculado: UILabel!
@IBOutlet weak var lblNomeMoeda: UILabel!
@IBOutlet weak var segControll: UISegmentedControl!
@IBOutlet weak var activityLoading: UIActivityIndicatorView!
@IBOutlet weak var segControll2: SegmentedControll!
@IBOutlet weak var imgLogo: UIImageView!
var valorMoeda:String = ""
var respostaJson:Double = 0.0
let conexao = Json()
override func viewDidLoad() {
super.viewDidLoad()
imgLogo.image = UIImage(named: "dolar")
segControll.layer.cornerRadius = CGRectGetHeight(segControll.bounds) / 2
segControll.layer.masksToBounds = true
segControll.layer.borderWidth = 1
segControll.layer.borderColor = UIColor.whiteColor().CGColor
segControll2.itens = ["Dolar","Euro","Libra"]
lblNomeMoeda.text = "DOLAR"
//txtvalor.attributedPlaceholder = NSAttributedString(string: "Digite o valor em Reais", attributes: [NSForegroundColorAttributeName : whiteColor])
txtvalor.attributedPlaceholder = NSAttributedString(string: "Digite o valor em Reais", attributes: [NSForegroundColorAttributeName : UIColor.whiteColor()])
conexao.ConexaoJson("USD") { (valor, error) in
dispatch_async(dispatch_get_main_queue()) {
if let valor = valor{
print("View Controller Valor ->", valor)
self.lblValorDefault.text = String(valor)
self.respostaJson = valor
self.activityLoading.stopAnimating()
}else{
print(error)
self.lblValorDefault.text = "Erro"
}
self.activityLoading.stopAnimating()
}
}
let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
// Do any additional setup after loading the view, typically from a nib.
}
func textFieldDidBeginEditing(textField: UITextField) {
moveTextField(txtvalor, moveDistance: -200, up: true)
}
func textFieldDidEndEditing(textField: UITextField) {
moveTextField(txtvalor, moveDistance: -200, up: false)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
txtvalor.resignFirstResponder()
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func segControll2(sender: UISegmentedControl) {
switch segControll2.selectedIndex {
case 0:
removeValores()
valorMoeda = "USD"
print(valorMoeda)
imgLogo.image = UIImage(named: "dolar")
lblNomeMoeda.text = "DOLAR"
case 1:
removeValores()
valorMoeda = "EUR"
print(valorMoeda)
imgLogo.image = UIImage(named: "euro")
lblNomeMoeda.text = "EURO"
case 2:
removeValores()
valorMoeda = "GBP"
print(valorMoeda)
imgLogo.image = UIImage(named: "libra")
lblNomeMoeda.text = "LIBRA"
default:
lblValorDefault.text = ""
txtvalor.text = ""
lblValorCalculado.text = ""
valorMoeda = "USD"
}
activityLoading.startAnimating()
conexao.ConexaoJson(valorMoeda) { (valor, error) in
dispatch_async(dispatch_get_main_queue()) {
if let valor = valor{
print("View Controller Valor ->", valor)
self.lblValorDefault.text = String(valor)
self.respostaJson = valor
self.activityLoading.stopAnimating()
}else{
print(error)
self.lblValorDefault.text = "Erro"
}
self.activityLoading.stopAnimating()
}
}
}
// @IBAction func segControllAction(sender: UISegmentedControl) {
//
// switch segControll.selectedSegmentIndex {
// case 0:
// valorMoeda = "USD"
// print(valorMoeda)
// imgLogo.image = UIImage(named: "dolar")
//
// case 1:
// valorMoeda = "EUR"
// print(valorMoeda)
// imgLogo.image = UIImage(named: "euro")
// case 2: //ARS
// valorMoeda = "GBP"
// print(valorMoeda)
// imgLogo.image = UIImage(named: "libra")
// default:
// valorMoeda = "USD"
// }
//
// activityLoading.startAnimating()
//
//
//
// conexao.ConexaoJson(valorMoeda) { (valor, error) in
// dispatch_async(dispatch_get_main_queue()) {
// if let valor = valor{
// print("View Controller Valor ->", valor)
//
//
// self.lblValorDefault.text = String(valor)
// self.respostaJson = valor
// self.activityLoading.stopAnimating()
//
//
// }else{
// print(error)
// self.lblValorDefault.text = "Erro"
// }
//
// self.activityLoading.stopAnimating()
// }
// }
//
// }
@IBAction func btnCalcular(sender: AnyObject) {
if txtvalor.text == "" {
let alert = UIAlertController(title: "Alerta", message: "Digite Algum Valor antes de Calcular", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
return
} else if self.lblValorDefault.text == "Erro"{
let alert = UIAlertController(title: "Alerta", message: "Verifique sua conexão antes de fazer o calculo", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
return
}
let converteValor = Multiplica()
let txtvalorDouble = Double(txtvalor.text!)
print(respostaJson)
let valorFinal = converteValor.multiplicacao(respostaJson, valor2: txtvalorDouble!)
lblValorCalculado.text = String(valorFinal)
view.endEditing(true)
}
func moveTextField(textField: UITextField, moveDistance: Int, up: Bool){
let moveDuration = 0.3
let movement:CGFloat = CGFloat(up ? moveDistance : -moveDistance)
UIView.beginAnimations("animateTextField", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(moveDuration)
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
func dismissKeyboard() {
view.endEditing(true)
}
func removeValores(){
lblValorDefault.text = ""
txtvalor.text = ""
lblValorCalculado.text = ""
}
}
|
//
// SettingsViewController.swift
// tips-calculator
//
// Created by Anh-Tu Hoang on 11/2/15.
// Copyright © 2015 hatu. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let defaults = NSUserDefaults.standardUserDefaults()
let percent = defaults.floatForKey("tip")
setTipPercentage(percent)
}
override func viewWillAppear(animated: Bool) {
}
private func setTipPercentage(percent: Float){
slrDefaultPercentage.value = percent
lblPercentage.text = String(format:"%d%%", Int(percent * 100))
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setFloat(percent, forKey: "tip")
defaults.synchronize()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var slrDefaultPercentage: UISlider!
@IBOutlet weak var lblPercentage: UILabel!
/*
// 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.
}
*/
@IBAction func onDefaultPercentage_Changing(sender: AnyObject) {
let percent = round(slrDefaultPercentage.value * 10) / 10
setTipPercentage(percent)
}
}
|
//
// User.swift
// App
//
// Created by Phanith Ny on 11/9/18.
//
import Foundation
import FluentSQLite
import Vapor
final class User: Codable {
var id: UUID?
var name: String
var username: String
init(name: String, username: String) {
self.name = name
self.username = username
}
}
extension User: SQLiteUUIDModel {}
extension User: Content {}
extension User: Migration {}
extension User: Parameter {}
|
//
// BalanceCollectionViewCell.swift
// Bulldog Bucks
//
// Created by Rudy Bermudez on 9/4/17.
//
//
import UIKit
class DetailCollectionViewCell: UICollectionViewCell {
public static let reuseIdentifier = "DetailCollectionViewCell"
@IBOutlet weak var amountLabel: UILabel!
@IBOutlet weak var weeklyLabel: UILabel!
}
|
//
// ExpenseDao.swift
// Splttng
//
// Created by Milo on 11/7/16.
// Copyright © 2016 ar.com.milohualpa. All rights reserved.
//
import Foundation
protocol ExpenseDAO {
func getAllExpenses() -> Array<Expense>
func getExpense(byId: Int) -> Expense
func removeExpense(byId: Int) -> Bool
func saveExpense(_: Expense) -> Bool
}
|
//
// Provider.swift
// Pods
//
// Created by Brendan Conron on 3/21/16.
//
//
import Foundation
public protocol Provider {
} |
import UIKit
final class KeyboardEvader: NSObject {
@IBOutlet private weak var scrollView: UIScrollView?
override func awakeFromNib() {
super.awakeFromNib()
registerForKeyboardNotifications()
}
private func registerForKeyboardNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(onShowKeyboard(_:)),
name: UIResponder.keyboardWillShowNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(onHideKeyboard(_:)),
name: UIResponder.keyboardWillHideNotification,
object: nil)
}
@objc private func onShowKeyboard(_ notification: Notification) {
guard let scrollView = scrollView else { return }
guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
let insets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardFrame.height, right: 0)
scrollView.contentInset = insets
scrollView.scrollIndicatorInsets = insets
}
@objc private func onHideKeyboard(_ notification: Notification) {
guard let scrollView = scrollView else { return }
scrollView.contentInset = .zero
scrollView.scrollIndicatorInsets = .zero
}
}
|
//
// ViewController.swift
// JobSpot-iOS
//
// Created by Krista Appel and Marlow Fernandez on 9/26/17.
// Copyright © 2017-2018 JobSpot. All rights reserved.
//
import UIKit
import Firebase
import LinkedinSwift
import Alamofire
import SwiftyJSON
class ProfileController: UIViewController {
var handle: FIRAuthStateDidChangeListenerHandle?
let logout = "logout"
let profileToHome = "profileToHome"
let profileToAppliedJobs = "profileToAppliedJobs"
let profileToSavedJobs = "profileToSavedJobs"
var fullName : String = " "
var email : String = " "
var headline : String = " "
var location : String = " "
var summary : String = " "
var picture : String = " "
var rootRef: FIRDatabaseReference!
var listRef: FIRDatabaseReference!
@IBOutlet weak var fullNameOutlet: UILabel!
@IBOutlet weak var headlineOutlet: UILabel!
@IBOutlet weak var emailOutlet: UILabel!
@IBOutlet weak var locationOutlet: UILabel!
@IBOutlet weak var summaryOutlet: UILabel!
@IBOutlet weak var profileImageOutlet: UIImageView!
@IBOutlet weak var logoutButtonOutlet: UIButton!
@IBOutlet weak var editProfileButtonOutlet: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.dismissKeyboardTapped()
fullNameOutlet.text = "N/A"
headlineOutlet.text = "N/A"
emailOutlet.text = "N/A"
locationOutlet.text = "N/A"
summaryOutlet.text = "N/A"
logoutButtonOutlet.backgroundColor = UIColor(hex: "CC0000")
editProfileButtonOutlet.backgroundColor = UIColor(hex: "CC0000")
rootRef = FIRDatabase.database().reference()
let userID = FIRAuth.auth()?.currentUser?.uid
let usersRef = self.rootRef.child("users")
let idRef = usersRef.child(userID!)
listRef = idRef.child("userProfile")
// if ProfileStruct.fullNameProf.lengthOfBytes(using: String.Encoding.utf8) > 0 {
// self.fullNameOutlet.text = ProfileStruct.fullNameProf
// }
//
// if ProfileStruct.headlineProf.lengthOfBytes(using: String.Encoding.utf8) > 0 {
// self.headlineOutlet.text = ProfileStruct.headlineProf
// }
//
// if ProfileStruct.locationProf.lengthOfBytes(using: String.Encoding.utf8) > 0 {
// self.locationOutlet.text = ProfileStruct.locationProf
// }
//
// if ProfileStruct.summaryProf.lengthOfBytes(using: String.Encoding.utf8) > 0 {
// self.summaryOutlet.text = ProfileStruct.summaryProf
// }
//
// if ProfileStruct.emailProf.lengthOfBytes(using: String.Encoding.utf8) > 0 {
// self.emailOutlet.text = ProfileStruct.emailProf
// }
//
// let urlPic = URL(string: ProfileStruct.pictureProf)
// if ProfileStruct.pictureProf.lengthOfBytes(using: String.Encoding.utf8) > 1 {
// let dataFromPic = try? Data(contentsOf: urlPic!)
// self.profileImageOutlet.image = UIImage(data: dataFromPic!)
// self.profileImageOutlet.setNeedsDisplay()
// }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
debugPrint("didReceiveMemoryWarning")
// Dispose of any resources that can be recreated.
}
@IBAction func logoutButtonAction(_ sender: Any) {
try! FIRAuth.auth()!.signOut()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
debugPrint("viewWillAppear")
handle = FIRAuth.auth()?.addStateDidChangeListener() { (auth, user) in
if user == nil {
self.performSegue(withIdentifier: self.logout, sender: nil)
}
}
listRef.observe(.value, with: { snapshot in
if snapshot.childrenCount == 0 {
self.fullNameOutlet.text = "N/A"
self.headlineOutlet.text = "N/A"
self.emailOutlet.text = "N/A"
self.locationOutlet.text = "N/A"
self.summaryOutlet.text = "N/A"
} else {
for item in snapshot.children {
debugPrint("item children: \(item)")
let profileItem = ProfileStruct(snapshot: item as! FIRDataSnapshot)
print("profileItem: \(profileItem)")
print("name \(profileItem.fullNameSave)")
print("email \(profileItem.emailSave)")
print("location \(profileItem.locationSave)")
print("headline \(profileItem.headlineSave)")
print("summary \(profileItem.summarySave)")
print("picture \(profileItem.pictureSave)")
if profileItem.fullNameSave.lengthOfBytes(using: String.Encoding.utf8) > 0 {
ProfileStruct.fullNameProf = profileItem.fullNameSave
} else {
ProfileStruct.fullNameProf = " "
}
if profileItem.headlineSave.lengthOfBytes(using: String.Encoding.utf8) > 0 {
ProfileStruct.headlineProf = profileItem.headlineSave
} else {
ProfileStruct.headlineProf = " "
}
if profileItem.locationSave.lengthOfBytes(using: String.Encoding.utf8) > 0 {
ProfileStruct.locationProf = profileItem.locationSave
} else {
ProfileStruct.locationProf = " "
}
if profileItem.summarySave.lengthOfBytes(using: String.Encoding.utf8) > 0 {
ProfileStruct.summaryProf = profileItem.summarySave
} else {
ProfileStruct.summaryProf = " "
}
if profileItem.emailSave.lengthOfBytes(using: String.Encoding.utf8) > 0 {
ProfileStruct.emailProf = profileItem.emailSave
} else {
ProfileStruct.emailProf = " "
}
if profileItem.pictureSave.lengthOfBytes(using: String.Encoding.utf8) > 0 {
ProfileStruct.pictureProf = profileItem.pictureSave
} else {
ProfileStruct.pictureProf = " "
}
DispatchQueue.main.async {
self.emailOutlet.text = ProfileStruct.emailProf
self.fullNameOutlet.text = ProfileStruct.fullNameProf
self.summaryOutlet.text = ProfileStruct.summaryProf
self.headlineOutlet.text = ProfileStruct.headlineProf
self.locationOutlet.text = ProfileStruct.locationProf
let urlPic = URL(string: ProfileStruct.pictureProf)
if ProfileStruct.pictureProf.lengthOfBytes(using: String.Encoding.utf8) > 5 {
let dataFromPic = try? Data(contentsOf: urlPic!)
if dataFromPic != nil {
self.profileImageOutlet.image = UIImage(data: dataFromPic!)
self.profileImageOutlet.setNeedsDisplay()
}
}
}
}
}
})
}
override func viewDidDisappear(_ animated: Bool) {
listRef.removeAllObservers()
}
@IBAction func signInLinkedIn(_ sender: UIButton) {
let alert = UIAlertController(title: "Profile", message: "Would you like to use your LinkedIn information for your profile?", preferredStyle: .alert)
let linkedInAction = UIAlertAction(title: "Yes", style: .default) { (action) in
LISDKSessionManager.createSession(withAuth: [LISDK_BASIC_PROFILE_PERMISSION], state: nil, showGoToAppStoreDialog: true, successBlock: {(success) in
//let session = LISDKSessionManager.sharedInstance().session
//let url = "https://api.linkedin.com/v1/people/~"
//let url = "https://api.linkedin.com/v1/people/~:(formatted-name,email-address,headline,location,industry,summary,picture-url)"
//debugPrint("url linkedin: \(url)")
let urlJson = "https://api.linkedin.com/v1/people/~:(formatted-name,email-address,headline,location,industry,summary,picture-url)?format=json"
// Alamofire.request(urlJson, method: .post).responseJSON { response in
//
// let jsonResponseLI = response.data
// let jsonResponseLIData = JSON(data: jsonResponseLI!)
//
// debugPrint("jsonResponseLIData: \(jsonResponseLIData)")
//
// }
//
if(LISDKSessionManager.hasValidSession()){
LISDKAPIHelper.sharedInstance().getRequest(urlJson, success: { (response) in
//print("response API linkedin: \(self.convertToDictionary(input: (response?.data)!)!)")
let jsonResponseLI = response?.data.data(using: String.Encoding.utf8, allowLossyConversion: false)
let jsonResponseLIData = JSON(data: jsonResponseLI!)
debugPrint("jsonResponseLIData: \(jsonResponseLIData)")
let formattedName = jsonResponseLIData["formattedName"].stringValue
if formattedName.lengthOfBytes(using: String.Encoding.utf8) > 0 {
self.fullName = formattedName
}
let headline = jsonResponseLIData["headline"].stringValue
if headline.lengthOfBytes(using: String.Encoding.utf8) > 0 {
self.headline = headline
}
let summary = jsonResponseLIData["summary"].stringValue
if summary.lengthOfBytes(using: String.Encoding.utf8) > 0 {
self.summary = summary
}
let pictureUrl = jsonResponseLIData["pictureUrl"].stringValue
if pictureUrl.lengthOfBytes(using: String.Encoding.utf8) > 0 {
self.picture = pictureUrl
}
let email = jsonResponseLIData["emailAddress"].stringValue
if email.lengthOfBytes(using: String.Encoding.utf8) > 0 {
self.email = email
}
print("formattedName: \(jsonResponseLIData["formattedName"].stringValue)") //
print("headline: \(jsonResponseLIData["headline"].stringValue)") //
print("summary: \(jsonResponseLIData["summary"].stringValue))") //
print("location: \(jsonResponseLIData["location"].arrayValue)") //
for locationResults in jsonResponseLIData["location"].arrayValue{
print("locationResults \(locationResults)")
}
print("pictureUrl: \(jsonResponseLIData["pictureUrl"].stringValue)") //
print("emailAddress: \(jsonResponseLIData["emailAddress"].stringValue)") //
// let profileStructItem = ProfileStruct(fullName: self.fullName, headline: self.headline, location: self.location, summary: self.summary, picture: self.picture, email: ProfileStruct.emailProf)
let profileItem = ProfileStruct(fullNameNew: self.fullName, headlineNew: self.headline, locationNew: self.location, summaryNew: self.summary, pictureNew: self.picture, emailNew: self.email)
print("profileItem: \(profileItem.emailSave)")
self.listRef.observe(.value, with: { snapshot in
print(snapshot.childrenCount)
if snapshot.childrenCount == 0 {
let addChildStr = self.listRef.childByAutoId()
addChildStr.setValue(profileItem.toAnyObject())
ProfileStruct.fullNameProf = profileItem.fullNameSave
ProfileStruct.headlineProf = profileItem.headlineSave
ProfileStruct.locationProf = profileItem.locationSave
ProfileStruct.summaryProf = profileItem.summarySave
ProfileStruct.pictureProf = profileItem.pictureSave
ProfileStruct.emailProf = profileItem.emailSave
DispatchQueue.main.async {
self.fullNameOutlet.text = ProfileStruct.fullNameProf
self.headlineOutlet.text = ProfileStruct.headlineProf
self.locationOutlet.text = ProfileStruct.locationProf
self.summaryOutlet.text = ProfileStruct.summaryProf
self.emailOutlet.text = ProfileStruct.emailProf
let urlPic = URL(string: ProfileStruct.pictureProf)
if ProfileStruct.pictureProf.lengthOfBytes(using: String.Encoding.utf8) > 0 {
let dataFromPic = try? Data(contentsOf: urlPic!)
self.profileImageOutlet.image = UIImage(data: dataFromPic!)
}
}
} else {
for item in snapshot.children {
let profileItem = ProfileStruct(snapshot: item as! FIRDataSnapshot)
print("profileItem: \(profileItem)")
let ref = profileItem.ref
print("ref from Profile: \(String(describing: ref))")
ref?.updateChildValues(["email": self.email])
ref?.updateChildValues(["fullName": self.fullName])
ref?.updateChildValues(["headline": self.headline])
ref?.updateChildValues(["location": self.location])
ref?.updateChildValues(["picture": self.picture])
ref?.updateChildValues(["summary": self.summary])
ProfileStruct.fullNameProf = self.fullName
ProfileStruct.headlineProf = self.headline
ProfileStruct.locationProf = self.location
ProfileStruct.summaryProf = self.summary
ProfileStruct.pictureProf = self.picture
ProfileStruct.emailProf = self.email
// DispatchQueue.main.async {
// self.fullNameOutlet.text = self.fullName
// self.headlineOutlet.text = self.headline
// self.locationOutlet.text = self.location
// self.summaryOutlet.text = self.summary
// self.emailOutlet.text = self.email
//
// let urlPic = URL(string: self.picture)
// debugPrint("urlPic: \(String(describing: urlPic))")
// if ProfileStruct.pictureProf.lengthOfBytes(using: String.Encoding.utf8) > 0 {
// let dataFromPic = try? Data(contentsOf: urlPic!)
// self.profileImageOutlet.image = UIImage(data: dataFromPic!)
// self.profileImageOutlet.setNeedsDisplay()
// }
// }
}
}
})
// ProfileStruct.fullNameProf = profileStructItem.fullName
// ProfileStruct.headlineProf = profileStructItem.headline
// ProfileStruct.locationProf = profileStructItem.location
// ProfileStruct.summaryProf = profileStructItem.summary
// ProfileStruct.pictureProf = profileStructItem.picture
// ProfileStruct.emailProf = profileStructItem.email
}, error: { (error) in
debugPrint("error response API Linkedin: \(error!)")
})
}
}
) { (error) in
debugPrint("error: \(String(describing: error))")
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(linkedInAction)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
}
func convertToDictionary(input: String)-> [String:Any]?{
if let info = input.data(using: .utf8){
do {
return try JSONSerialization.jsonObject(with: info, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
debugPrint("viewWillDisappear")
FIRAuth.auth()?.removeStateDidChangeListener(handle!)
}
}
|
//
// ExtraParser.swift
// caffinho-iOS
//
// Created by Rafael M. A. da Silva on 23/06/16.
// Copyright © 2016 venturus. All rights reserved.
//
import Foundation
import SwiftyJSON
class ExtraParser:Object {
struct ResponseKey {
static let name = "name"
static let price = "price"
}
class func extrasFromResponse(response:JSON) -> [Extra] {
var extras = [Extra]()
if let extrasFromResponse = response.array {
for extraFromResponse in extrasFromResponse {
if let extra = ExtraParser.objectFromResponse(extraFromResponse) as? Extra {
extras.append(extra)
}
}
}
return extras
}
}
extension ExtraParser:Parser {
class func responseIsValid(response: JSON) -> Bool {
//TODO complete it before
return true
}
class func objectFromResponse(response: JSON) -> Model? {
var extra:Extra?
if ExtraParser.responseIsValid(response) {
extra = Extra()
if let name = response[ResponseKey.name].string {
extra?.name = name
}
if let price = response[ResponseKey.price].string {
extra?.price = price
}
}
return extra
}
}
|
//: Playground - noun: a place where people can play
import UIKit
/**
* 泛型,在swift中可以说泛型无处不在,比如数组、字典,数组可以存储任意类型的值<T>(类型参数)只是告诉编译器T只是一个占位符,从而编译器不会去检查实际类型,而后面参数后的T,是表示这两个参数的类型必须是相同的。T可以用任意字符串(除了switf中关键字)代替
//<T>这是类型参数的定义方法,他紧跟方法名的后面,或者类型名的后面,多个类型参数可以放在尖括号里面,使用“,”分隔开。类型参数的命名使用开头大写的驼峰式命名
*/
//泛型函数
func swipTwoValus<T>(inout a:T, inout _ b:T){
let temp = a
a = b
b = temp
}
var a = 10
var b = 20
swipTwoValus(&a, &b)
print(a)
/**
* 自定泛型集类型,栈
*/
struct Stack<Element> {
private var items : [Element] = [Element]()
var top:Element?{
return items.count>0 ? items[items.endIndex-1]:nil
}
var bottom:Element{
return items[items.startIndex]
}
mutating func pop(){
assert(items.count>0, "no item")
items.removeLast()
}
mutating func push(item:Element){
items.append(item)
}
// init(bottom:Element){
// items = [Element]()
// self.push(bottom)
// }
}
var stack = Stack<String>()
stack.push("age")
stack.push("hello")
stack.pop()
print(stack.top!)
print(stack.bottom)
/**
* 类型约束,类型约束的语法,func somefunction<T:SomeClass, U:SomeProtocol>(t:T, u:U){}
*/
|
//
// TeamComp.swift
// TFT companion app
//
// Created by Sam Wayne on 8/11/19.
// Copyright © 2019 Sam Wayne. All rights reserved.
//
import Foundation
class TeamComp {
let type: Origin
let tier: originTier
init(type: Origin, tier: originTier) {
self.tier = tier
self.type = type
}
}
enum originTier {
case first
case second
case third
}
|
//
// Comments.swift
// UserInternetLoader
//
// Created by Apple on 10/6/20.
// Copyright © 2020 milic. All rights reserved.
//
import Foundation
class Comments {
var id:Int
var name:String
var email:String
var body:String
init (dict:[String:Any]){
id = dict["id"] as! Int
name = dict["name"] as! String
email = dict["email"] as! String
body = dict["body"] as! String
}
}
|
enum RoomName: String {
case tuna = "tuna"
case egg = "egg"
case salmonRoe = "salmon_roe"
static var names: Array<String> {
return [RoomName.tuna.rawValue, RoomName.egg.rawValue, RoomName.salmonRoe.rawValue]
}
}
|
//
// ViewController.swift
// Hello-World-World-Edition-Starter
//
// Learn Swift HK
//
//
import UIKit
class ViewController: UIViewController {
//----------------------------------------------------------------------------------
// MARK:- Properties
var greetings = ["Welcome",
"Velkommen",
"Welkom",
"歡迎",
"Bienvenue",
"Willkommen",
"ようこそ",
"Benvenuto",
"Välkommen",
"환영하다",
"Bienvenido",
"欢迎",
"Tervetuloa",
"Bem-vindo",
"Добро пожаловать"
]
var pressMes = ["Press Me",
"Trykk på Me",
"Druk op mij",
"按我",
"Appuyez-moi",
"Drück mich",
"私を押す",
"Premi Me",
"Tryck på Me",
"나를 압박해라",
"Presionarme",
"按我",
"Paina Me",
"Pressione-me",
"Нажмите Me"
]
//----------------------------------------------------------------------------------
// MARK:- Outlets
// TODO: Add AutoLayout Constraints for Welcome Label and Press Me button in Main.Storyboard
// TODO: Create Welcome Label and Press Me button in Main.Storyboard
// TODO: Add outlets for Welcome Label and Press Me button
//----------------------------------------------------------------------------------
// MARK:- Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//----------------------------------------------------------------------------------
// MARK:- Actions
// TODO: Add IBAction for Press Button, randomizing the greetings
// IBAction should trigger: 1) Welcome Label text change, 2) Press Me Button Title Change
//----------------------------------------------------------------------------------
}
|
//
// CDView.swift
//
// Created by 葛羽航 on 14/9/28.
//
import UIKit
class JSCanvasView: UIView {
var canvas : JSCanvas!
var ctx : JSContext!
private var _text : String = "Hello World! I love Guai!"
var text : String {
get {
return _text
}
set(text) {
_text = text
self.setNeedsDisplay()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.canvas = JSCanvas(view: self)
self.ctx = self.canvas.getContext("2d")
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.canvas = JSCanvas(view: self)
self.ctx = self.canvas.getContext("2d")
}
var _bg : String = "red"
var background : String {
get {
return _bg
}
set(bg) {
_bg = bg
}
}
var fontSize : CGFloat {
get {
return ctx.fontSize
}
set {
ctx.fontSize = 25
}
}
func paint() {
self.setNeedsDisplay()
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect)
{
ctx.setPaintContext(UIGraphicsGetCurrentContext())
//draw with ctx. just like javascript.
ctx.save()
ctx.fillStyle = self._bg
ctx.strokeStyle = self._bg
ctx.fillRect(10, top: 10, width: 100, height: 100)
ctx.strokeText(self._text, x: 10, y: 150)
ctx.strokeCircle(100, centerY: 200, radius: 46)
ctx.restore()
}
}
|
//
// CollectionViewCell.swift
// AlamofireApp
//
// Created by Vladislav on 23.06.2020.
// Copyright © 2020 Vladislav Cheremisov. All rights reserved.
//
import UIKit
class PhotoCell: UICollectionViewCell {
@IBOutlet var imageView: UIImageView!
@IBOutlet var activityIndicator: UIActivityIndicatorView!
override func awakeFromNib() {
super.awakeFromNib()
activityIndicator.startAnimating()
activityIndicator.hidesWhenStopped = true
}
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
}
}
|
// Copyright 2019-2022 Spotify AB.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import MobiusCore
@testable import MobiusNimble
import MobiusTest
import Nimble
import Quick
import XCTest
// The assertions in these tests are using XCTest assertions since the assertion handler for Nimble
// is replaced in order to be inspected
// swiftlint:disable file_length
// swiftlint:disable type_body_length
class NimbleNextMatchersTests: QuickSpec {
// swiftlint:disable function_body_length
override func spec() {
let assertionHandler = AssertionRecorder()
var defaultHandler: AssertionHandler?
describe("assertThatNext") {
beforeEach {
// A solution with `withAssertionHandler` (see Nimble documentation) doesn't work (the assertion handler
// is not being used inside the block).
// Doing a hack around it
defaultHandler = NimbleAssertionHandler
NimbleAssertionHandler = assertionHandler
}
afterEach {
NimbleAssertionHandler = defaultHandler!
}
let testUpdate = Update<String, String, String> { _, _ in
.next("some model", effects: ["some effect"])
}
// Testing through proxy: UpdateSpec
context("when asserting through predicates that fail") {
beforeEach {
UpdateSpec(testUpdate)
.given("a model")
.when("")
.then(assertThatNext(haveNoModel(), haveNoEffects()))
}
it("should have registered all failures") {
XCTAssertEqual(assertionHandler.assertions.count, 2)
}
}
}
describe("NimbleNextMatchers") {
beforeEach {
// A solution with `withAssertionHandler` (see Nimble documentation) doesn't work (the assertion handler
// is not being used inside the block).
// Doing a hack around it
defaultHandler = NimbleAssertionHandler
NimbleAssertionHandler = assertionHandler
}
afterEach {
NimbleAssertionHandler = defaultHandler!
}
context("when creating a matcher verifying that a Next has no model and no effects") {
let effects = [4]
let model = 1
context("when matching a Next that has no model and no effects") {
beforeEach {
let next = Next<Int, Int>.noChange
expect(next).to(haveNothing())
}
it("should match") {
assertionHandler.assertExpectationSucceeded()
}
}
context("when matching a Next that has a model but no effects") {
beforeEach {
let next = Next<Int, Int>.next(model)
expect(next).to(haveNothing())
}
it("should not match") {
assertionHandler.assertExpectationFailed()
}
}
context("when matching a Next that has effects but no model") {
beforeEach {
let next = Next<Int, Int>.dispatchEffects(effects)
expect(next).to(haveNothing())
}
it("should not match") {
assertionHandler.assertExpectationFailed()
}
}
context("when matching a Next that has model and effects") {
beforeEach {
let next = Next<Int, Int>.next(model, effects: effects)
expect(next).to(haveNothing())
}
it("should not match") {
assertionHandler.assertExpectationFailed()
}
}
context("when matching nil") {
beforeEach {
let next: Next<String, String>? = nil
expect(next).to(haveNothing())
}
it("should not match") {
assertionHandler.assertExpectationFailed()
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains(haveNonNilNext)
}
}
}
context("when creating a matcher to verify that a Next has a specific model") {
let expectedModel = "This is a model"
context("when matching a Next that has the specific model") {
beforeEach {
let next = Next<String, String>.next(expectedModel)
expect(next).to(haveModel(expectedModel))
}
it("should match") {
assertionHandler.assertExpectationSucceeded()
}
}
context("when matching a Next that does not have the specific model") {
let model = "some strange model"
beforeEach {
let next = Next<String, String>.next(model)
expect(next).to(haveModel(expectedModel))
}
it("should not match") {
assertionHandler.assertExpectationFailed()
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageHasSuffix("be <\(expectedModel)>, got <\(model)>")
}
}
context("when matching a Next that has no model") {
beforeEach {
let next = Next<String, String>.dispatchEffects(["cherry"])
expect(next).to(haveModel("apple"))
}
it("should not match") {
assertionHandler.assertExpectationFailed()
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageHasSuffix("have a model")
}
}
context("when matching nil") {
beforeEach {
let next: Next<String, String>? = nil
expect(next).to(haveModel("grapefruit"))
}
it("should not match") {
assertionHandler.assertExpectationFailed()
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains(haveNonNilNext)
}
}
}
context("when creating a matcher to verify that a Next has any model") {
context("when matching a Next with a model") {
let model = "lichi"
beforeEach {
let next = Next<String, String>.next(model)
expect(next).to(haveModel())
}
it("should match") {
assertionHandler.assertExpectationSucceeded()
}
}
context("when matching a Next without a model") {
beforeEach {
let next = Next<String, String>.dispatchEffects(["1", "3"])
expect(next).to(haveModel())
}
it("should not match") {
assertionHandler.assertExpectationFailed()
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageHasSuffix("not have a <nil> model")
}
}
context("when matching nil") {
beforeEach {
let next: Next<String, String>? = nil
expect(next).to(haveModel())
}
it("should not match") {
assertionHandler.assertExpectationFailed()
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains(haveNonNilNext)
}
}
}
context("when creating a matcher verifying that a Next has no model") {
context("when matching a Next that has no model") {
beforeEach {
let next = Next<String, String>.dispatchEffects(["1", "2"])
expect(next).to(haveNoModel())
}
it("should match") {
assertionHandler.assertExpectationSucceeded()
}
}
context("when matching a Next that has a different model") {
let model = "pomegranate"
beforeEach {
let next = Next<String, String>.next(model)
expect(next).to(haveNoModel())
}
it("should not match") {
assertionHandler.assertExpectationFailed()
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageHasSuffix("have no model, got <\(model)>")
}
}
context("when matching nil") {
beforeEach {
let next: Next<String, String>? = nil
expect(next).to(haveNoModel())
}
it("should not match") {
assertionHandler.assertExpectationFailed()
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains(haveNonNilNext)
}
}
}
context("when creating a matcher verifying that a Next has no effects") {
context("when matching a Next that has no effects") {
beforeEach {
let next = Next<String, String>.next("durian")
expect(next).to(haveNoEffects())
}
it("should match") {
assertionHandler.assertExpectationSucceeded()
}
}
context("when matching a Next that has effects") {
beforeEach {
let next = Next<String, String>.dispatchEffects(["durian"])
expect(next).to(haveNoEffects())
}
it("should not match") {
assertionHandler.assertExpectationFailed()
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains("have no effects")
}
}
context("when matching nil") {
beforeEach {
let next: Next<String, String>? = nil
expect(next).to(haveNoEffects())
}
it("should not match") {
assertionHandler.assertExpectationFailed()
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains(haveNonNilNext)
}
}
}
context("when creating a matcher verifying that a Next has specific effects") {
var expected: [Int]!
beforeEach {
expected = [4]
}
context("when the effects are the same") {
beforeEach {
let next = Next<String, Int>.dispatchEffects(expected)
expect(next).to(haveEffects(expected))
}
it("should match") {
assertionHandler.assertExpectationSucceeded()
}
}
context("when the Next contains the expected effects and a few more") {
let actual = [1, 2, 3, 4, 5, 0]
beforeEach {
let next = Next<String, Int>.dispatchEffects(actual)
expect(next).to(haveEffects(expected))
}
it("should match") {
assertionHandler.assertExpectationSucceeded()
}
}
context("when the Next does not contain one or more of the expected effects") {
var actual: [Int]!
beforeEach {
actual = [1]
let next = Next<String, Int>.dispatchEffects(actual)
expect(next).to(haveEffects(expected))
}
it("should not match") {
assertionHandler.assertExpectationFailed()
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains("contain <\(expected!)>, got <\(actual!)>")
}
}
context("when there are no effects") {
context("when not expecting effects") {
beforeEach {
let next = Next<String, Int>.noChange
expect(next).to(haveEffects([]))
}
it("should match") {
assertionHandler.assertExpectationSucceeded()
}
}
context("when expecting effects") {
beforeEach {
let next = Next<String, Int>.noChange
expect(next).to(haveEffects(expected))
}
it("should no match") {
assertionHandler.assertExpectationFailed()
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains("contain <\(expected!)>, got <[]>")
}
}
}
context("when matching nil") {
beforeEach {
let next: Next<String, Int>? = nil
expect(next).to(haveEffects(expected))
}
it("should no match") {
assertionHandler.assertExpectationFailed()
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains(haveNonNilNext)
}
}
}
context("when creating a matcher verifying that a Next has only specific effects") {
let expected = [1, 2, 3]
context("when the effects are the same") {
beforeEach {
let next = Next<String, Int>.dispatchEffects(expected)
expect(next).to(haveOnlyEffects(expected))
}
it("should match") {
assertionHandler.assertExpectationSucceeded()
}
}
context("when the effects are the same in different order") {
let actual = [3, 2, 1]
beforeEach {
let next = Next<String, Int>.dispatchEffects(actual)
expect(next).to(haveOnlyEffects(expected))
}
it("should match") {
assertionHandler.assertExpectationSucceeded()
}
}
context("when the Next contains the expected effects and a few more") {
let actual = [1, 2, 3, 4, 5, 0]
beforeEach {
let next = Next<String, Int>.dispatchEffects(actual)
expect(next).to(haveOnlyEffects(expected))
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains("contain only <\(expected)>, got <\(actual)>")
}
}
context("when the Next does not contain one or more of the expected effects") {
let actual = [1, 2]
beforeEach {
let next = Next<String, Int>.dispatchEffects(actual)
expect(next).to(haveOnlyEffects(expected))
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains("contain only <\(expected)>, got <\(actual)>")
}
}
context("when there are no effects") {
context("when not expecting effects") {
beforeEach {
let next = Next<String, Int>.noChange
expect(next).to(haveOnlyEffects([]))
}
it("should match") {
assertionHandler.assertExpectationSucceeded()
}
}
context("when expecting effects") {
beforeEach {
let next = Next<String, Int>.noChange
expect(next).to(haveOnlyEffects(expected))
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains("contain only <\(expected)>, got <[]>")
}
}
}
context("when matching nil") {
beforeEach {
let next: Next<String, Int>? = nil
expect(next).to(haveOnlyEffects(expected))
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains(haveNonNilNext)
}
}
}
context("when creating a matcher verifying that a Next has exact effects") {
let expected = [1, 2, 3]
context("when the effects are the same") {
beforeEach {
let next = Next<String, Int>.dispatchEffects(expected)
expect(next).to(haveExactlyEffects(expected))
}
it("should match") {
assertionHandler.assertExpectationSucceeded()
}
}
context("when the effects are the same in different order") {
let actual = [3, 2, 1]
beforeEach {
let next = Next<String, Int>.dispatchEffects(actual)
expect(next).to(haveExactlyEffects(expected))
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains("equal <\(expected)>, got <\(actual)>")
}
}
context("when the Next contains the expected effects and a few more") {
let actual = [1, 2, 3, 4, 5, 0]
beforeEach {
let next = Next<String, Int>.dispatchEffects(actual)
expect(next).to(haveExactlyEffects(expected))
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains("equal <\(expected)>, got <\(actual)>")
}
}
context("when the Next does not contain one or more of the expected effects") {
let actual = [1, 2]
beforeEach {
let next = Next<String, Int>.dispatchEffects(actual)
expect(next).to(haveExactlyEffects(expected))
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains("equal <\(expected)>, got <\(actual)>")
}
}
context("when there are no effects") {
context("when not expecting effects") {
beforeEach {
let next = Next<String, Int>.noChange
expect(next).to(haveExactlyEffects([]))
}
it("should match") {
assertionHandler.assertExpectationSucceeded()
}
}
context("when expecting effects") {
beforeEach {
let next = Next<String, Int>.noChange
expect(next).to(haveExactlyEffects(expected))
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains("equal <\(expected)>, got <[]>")
}
}
}
context("when matching nil") {
beforeEach {
let next: Next<String, Int>? = nil
expect(next).to(haveExactlyEffects(expected))
}
it("should produce an appropriate error message") {
assertionHandler.assertLastErrorMessageContains(haveNonNilNext)
}
}
}
}
}
}
|
//
// Potential Match.swift
// Pyromance
//
// Created by Danielle Nunez on 12/12/18.
//
import Foundation
class PotentialMatch {
let username: String!
let image: String!
let server: String!
let level: String!
let characterClass: String!
init(username: String, image: String, server: String, level: String) {
self.username = username
self.image = image
self.server = server
self.level = level
self.characterClass = "Hunter"
}
init(username: String, image: String) {
self.username = username
self.image = image
self.server = "Stormrage"
self.level = "120"
self.characterClass = "Hunter"
}
/*
Returns the username in the form <name>-<server>
i.e. Skarmorite-Stormrage
*/
func getFullUsername() -> String{
return self.username + "-" + self.server
}
}
|
//
// UIImage+extension.swift
// zuidilao
//
// Created by 张凯强 on 2019/9/23.
// Copyright © 2019年 张凯强. All rights reserved.
//
import Foundation
extension UIImage {
class func ImageWithColor(color: UIColor, frame: CGRect) -> UIImage? {
let aframe = CGRect.init(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
UIGraphicsBeginImageContext(frame.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(aframe)
let theImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return theImage
}
convenience init(gradientColors:[UIColor], bound: CGRect) {
UIGraphicsBeginImageContextWithOptions(bound.size, true, 0)
let context = UIGraphicsGetCurrentContext()
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colors = gradientColors.map { (color) -> CGColor in
return color.cgColor
}
let gradient = CGGradient.init(colorsSpace: colorSpace, colors: colors as CFArray, locations: nil)
if let grad = gradient {
context?.drawLinearGradient(grad, start: CGPoint.init(x: 0, y: 0), end: CGPoint.init(x: bound.width, y: 0), options: CGGradientDrawingOptions.init(rawValue: 0))
}
if let image = UIGraphicsGetImageFromCurrentImageContext()?.cgImage {
self.init(cgImage: image)
UIGraphicsEndImageContext()
}else {
self.init()
}
}
}
extension UIImage{
func compressImageSize() -> UIImage {
// let ddj = ByteCountFormatter.string(fromByteCount: 1024, countStyle: ByteCountFormatter.CountStyle.binary)
let dd = self.jpegData(compressionQuality: 1)
if dd?.count ?? 0 > (1024 * 1024){//压缩到大概1M以下
UIGraphicsBeginImageContextWithOptions(self.size, true, 0.5)
self.draw(in: CGRect(x: 0, y: 0, width: self.size.width , height: self.size.height ))
if let newImage = UIGraphicsGetImageFromCurrentImageContext(){
UIGraphicsEndImageContext();
guard let data = newImage.jpegData(compressionQuality: 1) else{
return newImage
}
guard let convertImage = UIImage(data: data) else{return newImage}
return convertImage.compressImageSize()
}else{
return self
}
}else{return self}
}
/// compressImageQuality
///
/// - Parameters:
/// - quality: 0.0 ~ 1.0, 1.0 is the best quality
func compressImageQuality( quality : CGFloat) -> UIImage {
guard let data = self.jpegData(compressionQuality: 1) else{
return self
}
guard let convertImage = UIImage(data: data) else{return self}
return convertImage
}
///在图片上画文字
func addshopMediaStr(str: String, strRect: CGRect? = nil) -> UIImage {
let returnImageSize = CGSize(width: 360 , height: 1080)
UIGraphicsBeginImageContextWithOptions(CGSize.init(width: 360, height: 1080), false, 0)
self.draw(in: CGRect.init(x: 0, y: 0, width: returnImageSize.width, height: returnImageSize.height))
let context = UIGraphicsGetCurrentContext()
context?.drawPath(using: CGPathDrawingMode.stroke)
let nsStr = NSString.init(string: str)
let strSize = str.sizeWith(font: UIFont.systemFont(ofSize: 18), maxSize: CGSize.init(width: 360, height: 80))
let waterW:CGFloat = strSize.width
let waterH : CGFloat = strSize.height
let waterX : CGFloat = returnImageSize.width - 10 - waterW
let waterY:CGFloat = returnImageSize.height - waterH - 10
nsStr.draw(at: CGPoint.init(x: waterX, y:waterY), withAttributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.white.withAlphaComponent(0.7)])
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndPDFContext()
if let image = newImage {
return image
}else {
return UIImage.init()
}
}
func addWaterImage(_ waterImage : UIImage , waterImageRect : CGRect? = nil) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, true, 0)// 0 不压缩
self.draw(in: CGRect(x: 0, y: 0, width: self.size.width , height: self.size.height))
let waterImageRect = waterImageRect
if let waterImageRect = waterImageRect{
waterImage.draw(in: waterImageRect)
}else{
let waterSizeScale = self.size.width/8 * 6 / waterImage.size.width
let waterW:CGFloat = waterImage.size.width * waterSizeScale
let waterH : CGFloat = waterImage.size.height * waterSizeScale
let waterX : CGFloat = self.size.width/8
let waterY:CGFloat = self.size.height/2 - waterH/2
let waterRect = CGRect(x: waterX, y: waterY, width: waterW, height: waterH)
waterImage.draw(in: waterRect)
}
if let newImage = UIGraphicsGetImageFromCurrentImageContext(){
UIGraphicsEndImageContext();
let data = newImage.jpegData(compressionQuality: 1)////最好一个参数起压缩作用
guard let convertImage = UIImage(data: data!) else{return self}
return convertImage
}else{
return self
}
// UIGraphicsEndImageContext();
// let data = UIImageJPEGRepresentation(newImage!, 1)////最好一个参数起压缩作用
// guard let convertImage = UIImage(data: data!) else{return self}
// return convertImage
}
func writeImage(filePathLastComponent:String? = nil ) {
let data = self.jpegData(compressionQuality: 1)
var homePathOrigin = NSHomeDirectory()
if let filePathLastComponent = filePathLastComponent{
homePathOrigin.append("/Library/\(filePathLastComponent)")
}else{
let fileName = "/Library/\(Date().timeIntervalSince1970)"
homePathOrigin.append("\(fileName).jpeg")
}
let result1 = try? data?.write(to: URL(fileURLWithPath: homePathOrigin))
}
///张凯强添加水印的图片
func addWaterImage(_ waterImage : UIImage? = UIImage.init(named: "water")) -> UIImage {
let backgroundImage = self.compressImageQuality(quality: 0.1)
let img = backgroundImage.compressImageSize()
let img2 = img.addWaterImage(waterImage ?? UIImage.init(), waterImageRect: nil)
let img3 = img2.compressImageQuality(quality: 0.1)
let img4 = img3.compressImageSize()
return img4
}
class func getImage(startColor:UIColor , endColor:UIColor ,startPoint:CGPoint , endPoint:CGPoint , size:CGSize) -> UIImage?{
let gradientLayer = CAGradientLayer.init()
gradientLayer.frame = CGRect(origin: CGPoint.zero, size: size)
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
gradientLayer.startPoint = startPoint
gradientLayer.endPoint = endPoint
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
let imageRet = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageRet
}
}
import UIKit
import SDWebImage
extension UIImageView {
func setImageUrl(url:String? , placeHolderImage:UIImage? = nil ) {
if let urlStr = url , let urlInstence = URL(string: urlStr){
self.sd_setImage(with: urlInstence, placeholderImage:placeHolderImage ?? DDPlaceholderImage, options: [SDWebImageOptions.retryFailed,SDWebImageOptions.cacheMemoryOnly])
}else{
if let pImage = placeHolderImage{
self.image = pImage
}else{
self.image = DDPlaceholderImage
}
}
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
extension UIButton {
func setImageUrl(url:String? , status : UIControl.State = .normal) {
if let urlStr = url , let urlInstence = URL(string: urlStr){
self.sd_setImage(with: urlInstence, for: status, placeholderImage: DDPlaceholderImage, options: [SDWebImageOptions.retryFailed,SDWebImageOptions.cacheMemoryOnly])
}else{
self.setImage(DDPlaceholderImage, for: status)
}
}
func setBackgroundImageUrl(url:String?,placeholderImage:UIImage , status : UIControl.State = .normal) {
if let urlStr = url , let urlInstence = URL(string: urlStr){
// self.sd_setBackgroundImage
// self.sd_setBackgroundImage(with: urlInstence, for: status)
self.sd_setBackgroundImage(with: urlInstence, for: status, placeholderImage: placeholderImage, options: [SDWebImageOptions.retryFailed,SDWebImageOptions.cacheMemoryOnly])
// self.sd_setImage(with: urlInstence, for: status, placeholderImage: DDPlaceholderImage, options: [SDWebImageOptions.retryFailed,SDWebImageOptions.cacheMemoryOnly])
}else{
self.setImage(DDPlaceholderImage, for: status)
}
}
}
|
//
// DIYRefreshView.swift
// DIYRefresh
//
// Created by SunnyMac on 16/11/23.
// Copyright © 2016年 hjl. All rights reserved.
//
import UIKit
// 单条线颜色的停留时间
let kloadingIndividualAnimationTiming : CGFloat = 1
// 透明度
let kbarDarkAlpha : CGFloat = 0.4
// 偏移时间, 也就是刷新时动画的单位时间
let kloadingTimingOffset : CGFloat = 0.1
// 消失的时间
let kdisappearDuration : CGFloat = 0.8
// 相对高度
let krelativeHeightFactor : CGFloat = 2.0/5
let kinternalAnimationFactor : CGFloat = 0.7
let startPointKey = "startPoints"
let endPointKey = "endPoints"
let kDIYRefreshContentOffset = "contentOffset"
enum DIYRefreshState {
case normal
case refreshing
case disappearing
}
class DIYRefreshView: UIView {
var state : DIYRefreshState = .normal
var barItems : [DIYBarItem] = [DIYBarItem]()
var scrollView : UIScrollView?
var displayLink : CADisplayLink?
var target : AnyObject?
var action : Selector?
var finishedCallback : (() -> ())?
var lineCount : Int = 0
var showStyle: Int = 0
var dropHeight : CGFloat = 0.0
var originalContentInsetTop : CGFloat = 64.0
var disappearProgress : CGFloat = 0.0
var horizontalRandomness : Int = 0
var isReverseLoadingAnimation : Bool = false
var refreshTime : CGFloat = 0
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
/// 为scrollView的contentOffset属性, 添加一个监听者
newSuperview?.addObserver(self, forKeyPath: kDIYRefreshContentOffset, options: .new, context: nil)
/// 保存父控件, 都还是原始值, 此时scrollView还没有自动偏移
scrollView = newSuperview as? UIScrollView
scrollView?.autoresizesSubviews = false
}
// 监听UIScrollView的contentOffset属性
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (kDIYRefreshContentOffset == keyPath) {
self.adjustStateWithContentOffset()
}
}
}
extension DIYRefreshView {
class func attach(scrollView: UIScrollView,
plist: String,
target: AnyObject,
refreshAction: Selector,
color: UIColor)
-> DIYRefreshView {
return self.attach(scrollView: scrollView, plist: plist, target: target, refreshAction: refreshAction, color: color, lineWidth: 5, dropHeight: 80, scale: 0.8, showStyle: 0, horizontalRandomness: 150, isReverseLoadingAnimation: false, finishedCallback: nil)
}
class func attach(scrollView: UIScrollView,
plist: String,
color: UIColor,
finishedCallback: (() -> ())?
) -> DIYRefreshView {
return self.attach(scrollView: scrollView, plist: plist, target: nil, refreshAction: nil, color: color, lineWidth: 5, dropHeight: 80, scale: 0.8, showStyle: 0, horizontalRandomness: 150, isReverseLoadingAnimation: false, finishedCallback: finishedCallback)
}
/// 刷新控件的创建方式
///
/// - Parameters:
/// - scrollView: 将刷新控件添加到的scrollView对象(可以是scrollView的子类)
/// - plist: 刷新图案的坐标集合
/// - target: 调用此刷新控件的控制器
/// - refreshAction: 刷新时的刷新事件
/// - color: 刷新控件的内容颜色
/// - lineWidth: 刷新控件的线条宽度
/// - dropHeight: 刷新控件的偏移高度
/// - scale: 刷新控件内容的缩放比例(1.0为原生值)
/// - showStyle: 刷新控件的风格(0:飞来风格, 1:淡入淡出)
/// - horizontalRandomness: 产生随机数的水平方向上的值, 可以用来改变飞来风格的初始坐标值
/// - isReverseLoadingAnimation: 是否反向加载动画
/// - finishedCallback: 刷新回调方法
class func attach(scrollView: UIScrollView,
plist: String,
target: AnyObject?,
refreshAction: Selector?,
color: UIColor = .red,
lineWidth: CGFloat = 5,
dropHeight: CGFloat = 80,
scale: CGFloat = 0.8,
showStyle: Int = 0,
horizontalRandomness: CGFloat = 150,
isReverseLoadingAnimation: Bool = false,
finishedCallback: (() -> ())?
) -> DIYRefreshView {
/// 创建
let diyRefresh = DIYRefreshView()
diyRefresh.dropHeight = dropHeight
diyRefresh.horizontalRandomness = Int(horizontalRandomness)
diyRefresh.scrollView = scrollView
diyRefresh.target = target as AnyObject?
diyRefresh.action = refreshAction
diyRefresh.showStyle = showStyle
diyRefresh.isReverseLoadingAnimation = isReverseLoadingAnimation
diyRefresh.finishedCallback = finishedCallback
/// 添加控件
scrollView.addSubview(diyRefresh)
var width : CGFloat = 0
var height : CGFloat = 0
/// 字典数据, plist 转 字典
let str = Bundle.main.path(forResource: plist, ofType: "plist")
let rootDictionary : NSMutableDictionary = NSMutableDictionary.init(contentsOfFile: str!)!
var startPoints : [String] = rootDictionary.object(forKey: startPointKey) as! [String]
var endPoints : [String] = rootDictionary.object(forKey: endPointKey) as! [String]
diyRefresh.lineCount = startPoints.count
diyRefresh.refreshTime = CGFloat(diyRefresh.lineCount) * kloadingTimingOffset * 2
for i in 0 ..< startPoints.count {
let startPoint : CGPoint = CGPointFromString(startPoints[i])
let endPoint : CGPoint = CGPointFromString(endPoints[i])
if startPoint.x > width {width = startPoint.x}
if endPoint.x > width {width = endPoint.x}
if startPoint.y > height {height = startPoint.y}
if endPoint.y > height {height = endPoint.y}
}
diyRefresh.frame = CGRect.init(x: 0, y: 0, width: (width + lineWidth), height: (height + lineWidth))
var mutableBarItems : [DIYBarItem] = [DIYBarItem]()
for i in 0 ..< startPoints.count {
let startPoint : CGPoint = CGPointFromString(startPoints[i])
let endPoint : CGPoint = CGPointFromString(endPoints[i])
// 创建barItem
let barItem : DIYBarItem = DIYBarItem.init(frame: diyRefresh.frame, startPoint: startPoint, endPoint: endPoint, color: color, lineWidth: lineWidth)
barItem.tag = i
barItem.backgroundColor = UIColor.clear
barItem.alpha = 0
mutableBarItems.append(barItem)
diyRefresh.addSubview(barItem)
barItem.setHorizontalRandomness(horizontalRandomness: diyRefresh.horizontalRandomness, dropHeight: diyRefresh.dropHeight)
}
diyRefresh.barItems = mutableBarItems
for barItem in diyRefresh.barItems {
barItem.setupWithFrame(rect: diyRefresh.frame)
}
diyRefresh.transform = CGAffineTransform.init(scaleX: scale, y: scale)
return diyRefresh
}
}
extension DIYRefreshView{
func realContentOffsetY() -> CGFloat {
return self.scrollView!.contentOffset.y + self.originalContentInsetTop;
}
/// 动画的进度
func animationProgress() -> CGFloat {
let x = fabsf(Float(self.realContentOffsetY()))
let y = max(Double(0), Double(x / Float(self.dropHeight)))
return CGFloat(min(1.0, y))
}
/// 开始加载动画
func startLoadingAnimation() {
/// 反向加载动画
if (self.isReverseLoadingAnimation) {
let count : Int = self.barItems.count
for j in 0 ..< (self.barItems).count {
let i = count - j - 1
let barItem = self.barItems[i]
self.perform(#selector(barItemAnimation), with: barItem, afterDelay: TimeInterval(CGFloat(i) * kloadingTimingOffset), inModes: [.commonModes])
}
}/// 正向加载动画
else {
for i in 0 ..< self.barItems.count {
let barItem = self.barItems[i]
self.perform(#selector(barItemAnimation), with: barItem, afterDelay: TimeInterval(CGFloat(i) * kloadingTimingOffset), inModes: [.commonModes])
}
}
}
// baritem的动画
func barItemAnimation(barItem: DIYBarItem) {
// 正在刷新中...
if self.state == DIYRefreshState.refreshing {
barItem.alpha = 1
// 移除动画
barItem.layer.removeAllAnimations()
// 定时将线条的颜色还原
UIView.animate(withDuration: TimeInterval(kloadingIndividualAnimationTiming), animations: {
barItem.alpha = kbarDarkAlpha
})
var isLastOne = true
if self.isReverseLoadingAnimation {
isLastOne = barItem.tag == 0
} else {
isLastOne = barItem.tag == self.barItems.count - 1
if isLastOne && self.state == DIYRefreshState.refreshing {
// 开始第二遍动画, 递归,无出口, 形成死循环, 会一直刷新
// 不延时的话, 下一遍的第一个线段 会和 上一次的最后一个线段, 同时显示
DispatchQueue.main.asyncAfter(deadline: .now() + TimeInterval(kloadingTimingOffset)) {
self.startLoadingAnimation()
}
}
}
}
}
// 更新消失动画
func updateDisappearAnimation() {
if self.disappearProgress >= 0 && self.disappearProgress <= 1 {
// iOS设备的刷新频率事60HZ也就是每秒60次。那么每一次刷新的时间就是1/60秒 大概16.7毫秒
self.disappearProgress -= 1.0/60.0/kdisappearDuration
self.updateBarItems(progress: self.disappearProgress)
}
}
func updateBarItems(progress: CGFloat) {
for (index,barItem) in (self.barItems).enumerated() {
let startPadding : CGFloat = (1.0 - kinternalAnimationFactor) / CGFloat(self.barItems.count) * CGFloat(index)
let endPadding : CGFloat = 1 - kinternalAnimationFactor - startPadding
if (progress == 1 || progress >= 1 - endPadding) {
barItem.transform = CGAffineTransform.identity
barItem.alpha = kbarDarkAlpha
}else if (progress == 0) {
barItem.setHorizontalRandomness(horizontalRandomness: self.horizontalRandomness, dropHeight: self.dropHeight)
}else {
var realProgress : CGFloat = 0
if (progress <= startPadding){
realProgress = 0
}
else {
realProgress = CGFloat(min(1.0,(progress - startPadding)/kinternalAnimationFactor))
if self.showStyle == 0 {
barItem.transform = CGAffineTransform.init(translationX: barItem.translationX*(1-realProgress), y: -self.dropHeight*(1-realProgress))
barItem.transform = barItem.transform.rotated(by: 3.14*realProgress)
barItem.transform = barItem.transform.scaledBy(x: realProgress, y: realProgress)
}
barItem.alpha = realProgress * kbarDarkAlpha
}
}
}
}
// 完成加载
func finishingLoading() {
self.state = DIYRefreshState.disappearing
UIView.animate(withDuration: TimeInterval(kdisappearDuration), animations: {
self.scrollView?.contentInset.top = self.originalContentInsetTop
}) { (Bool) in
// 状态设置为:正常
self.state = DIYRefreshState.normal
self.displayLink?.invalidate()
self.disappearProgress = 1
}
// 所有的动画都移除, 并且颜色都还原
for barItem in self.barItems {
barItem.layer.removeAllAnimations()
barItem.alpha = kbarDarkAlpha
}
self.displayLink = CADisplayLink.init(target: self, selector: #selector(updateDisappearAnimation))
self.displayLink?.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
self.disappearProgress = 1
}
}
extension DIYRefreshView : UIScrollViewDelegate{
func adjustStateWithContentOffset(){
self.center = CGPoint.init(x: UIScreen.main.bounds.size.width/2, y: self.realContentOffsetY() * krelativeHeightFactor)
// 如果正在拖动
if (self.scrollView?.isDragging)! {
if self.originalContentInsetTop == 0 {
self.originalContentInsetTop = (self.scrollView?.contentInset.top)!
}
if self.state == DIYRefreshState.normal {
self.updateBarItems(progress: self.animationProgress())
}
}// 手松开
else{
// 松手就会刷新的状态
if (self.state == DIYRefreshState.normal && self.realContentOffsetY() < -self.dropHeight) {
if (self.animationProgress() == CGFloat(1)) {
self.state = DIYRefreshState.refreshing
}
if (self.state == DIYRefreshState.refreshing) {
var newInsets : UIEdgeInsets = self.scrollView!.contentInset
newInsets.top = self.originalContentInsetTop + self.dropHeight
let contentOffset : CGPoint = self.scrollView!.contentOffset
UIView.animate(withDuration: 0, animations: {
self.scrollView?.contentInset = newInsets
self.scrollView?.contentOffset = contentOffset
})
if (self.target?.responds(to: self.action))! {
self.target?.perform(self.action!, with: nil, afterDelay: TimeInterval(self.refreshTime), inModes: [RunLoopMode.commonModes])
}
if ((self.finishedCallback) != nil) {
DispatchQueue.main.asyncAfter(deadline: .now() + TimeInterval(self.refreshTime)) {
self.finishedCallback!()
}
}
// 开始第一遍动画
self.startLoadingAnimation()
}
} else{
// 还原成最初的设置
self.updateBarItems(progress: self.animationProgress())
}
}
}
}
|
import SwiftUI
struct EventListCardView: View {
@EnvironmentObject var homeViewModel: HomeViewModel
@State var post: Event
@Binding var showNav : Bool
var body: some View {
HStack {
VStack(alignment: .leading) {
Text(post.GetTitle()).listTitleText()
HStack{
Text(post.GetLocationType().rawValue).listLocationTypeText()
Spacer()
Text(post.GetLocationToShow()).listLocationToShowText()
}.padding(.leading,3).padding(.trailing,5)
HStack{
Text(post.GetDateToShow()).listDateToShowText()
Spacer()
ListEventStats(likeCount: post.GetLikeCount(),hasliked: post.GetHasLiked(), joinCount: post.GetJoinCount(),hasJoined: post.GetHasUserJoined())
}.padding(.leading,3).padding(.trailing,5)
}.padding(.all,3)
}.listCard().onTapGesture {
guard let index = self.homeViewModel.activePostList.firstIndex(of: self.post)else{return}
self.homeViewModel.currentPost = index
self.homeViewModel.showingEventList.toggle()
self.showNav.toggle()
}
}
}
|
//
// LoginViewController.swift
// PasswordKeeper
//
// Created by Tyler Rockwood on 3/6/16.
// Copyright © 2016 Rose-Hulman. All rights reserved.
//
import UIKit
import Material
import Firebase
import Rosefire
class LoginViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var emailTextField: TextField!
@IBOutlet weak var passwordTextField: TextField!
@IBOutlet weak var emailPasswordLoginButton: RaisedButton!
@IBOutlet weak var rosefireLoginButton: RaisedButton!
@IBOutlet weak var googleLoginButton: GIDSignInButton!
// MARK: - Login Methods
var loginClosure: FIRAuthResultCallback {
get {
// let loadingDialog = NBMaterialLoadingDialog.showLoadingDialogWithText(view, message: "Logging In...")
return { (user, err) in
// loadingDialog.hideDialog()
if err == nil {
self.appDelegate.handleLogin()
} else {
let alertController = UIAlertController(title: "Login failed", message: "", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
print(err?.localizedDescription)
print(err?.description)
}
}
}
}
@IBAction func emailPasswordLogin(sender: AnyObject) {
FIRAuth.auth()?.signInWithEmail(emailTextField.text!, password: passwordTextField.text!, completion: loginClosure)
}
@IBAction func rosefireLogin(sender: AnyObject) {
Rosefire.sharedDelegate().uiDelegate = self // This should be your view controller
Rosefire.sharedDelegate().signIn(ROSEFIRE_TOKEN) { (err, token) in
if err == nil {
FIRAuth.auth()?.signInWithCustomToken(token, completion: self.loginClosure)
}
}
}
@IBAction func googleLogin(sender: AnyObject) {
self.dismissViewControllerAnimated(true) {
GIDSignIn.sharedInstance().signIn()
}
}
// Implement the required GIDSignInDelegate methods
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
withError error: NSError!) {
if let error = error {
print(error.localizedDescription)
return
}
let authentication = user.authentication
let credential = FIRGoogleAuthProvider.credentialWithIDToken(authentication.idToken, accessToken: authentication.accessToken)
print("Credential = \(credential.provider)")
FIRAuth.auth()?.signInWithCredential(credential, completion: loginClosure)
}
// Implement the required GIDSignInDelegate methods
// Unauth when disconnected from Google
func signIn(signIn: GIDSignIn!, didDisconnectWithUser user:GIDGoogleUser!,
withError error: NSError!) {
try! FIRAuth.auth()?.signOut()
}
// MARK: - View Methods
override func viewDidLoad() {
super.viewDidLoad()
prepareView()
// Setup delegates
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
// Attempt to sign in silently, this will succeed if
// the user has recently been authenticated
// GIDSignIn.sharedInstance().signInSilently()
}
func prepareView() {
self.view.backgroundColor = MaterialColor.indigo.base
titleLabel.font = RobotoFont.thinWithSize(36)
googleLoginButton.style = .Wide
var textField = emailTextField
textField.placeholder = "Email"
textField.placeholderColor = MaterialColor.grey.lighten4
textField.font = RobotoFont.regularWithSize(20)
textField.textColor = MaterialColor.white
textField.backgroundColor = MaterialColor.clear
textField.font = RobotoFont.mediumWithSize(12)
textField.textColor = MaterialColor.white
// textField.textActiveColor = MaterialColor.white
/*
Used to display the error message, which is displayed when
the user presses the 'return' key.
*/
textField.detailLabel.text = "Email is incorrect."
textField.detailLabel.font = RobotoFont.mediumWithSize(12)
// textField.detailLabel.activeColor = MaterialColor.red.accent3
// textField.detailLabelAutoHideEnabled = false // Uncomment this line to have manual hiding.
let image = UIImage(named: "ic_close_white")?.imageWithRenderingMode(.AlwaysTemplate)
textField.clearIconButton?.pulseColor = MaterialColor.grey.lighten4
// clearButton.pulseScale = false
textField.clearIconButton?.tintColor = MaterialColor.grey.lighten4
textField.clearIconButton?.setImage(image, forState: .Normal)
textField.clearIconButton?.setImage(image, forState: .Highlighted)
// Set up password field
textField = passwordTextField
textField.placeholder = "Password"
textField.placeholderColor = MaterialColor.grey.lighten4
textField.font = RobotoFont.regularWithSize(20)
textField.textColor = MaterialColor.white
textField.backgroundColor = MaterialColor.clear
textField.font = RobotoFont.mediumWithSize(12)
textField.textColor = MaterialColor.white
// textField.titleLabelActiveColor = MaterialColor.white
textField.clearIconButton?.pulseColor = MaterialColor.grey.lighten4
// clearButton.pulseScale = false
textField.clearIconButton?.tintColor = MaterialColor.grey.lighten4
textField.clearIconButton?.setImage(image, forState: .Normal)
textField.clearIconButton?.setImage(image, forState: .Highlighted)
emailPasswordLoginButton.setTitle("Email/Password Login", forState: .Normal)
emailPasswordLoginButton.titleLabel!.font = RobotoFont.mediumWithSize(18)
emailPasswordLoginButton.backgroundColor = MaterialColor.indigo.darken2
rosefireLoginButton.setTitle("Rosefire Login", forState: .Normal)
rosefireLoginButton.titleLabel!.font = RobotoFont.mediumWithSize(18)
rosefireLoginButton.backgroundColor = MaterialColor.indigo.darken2
}
}
|
//
// HomeUseCases.swift
// UnsplashClient
//
// Created by Ness Bautista on 08/07/20.
// Copyright © 2020 Ness Bautista. All rights reserved.
//
import Foundation
import Combine
protocol HomeUseCasesProtocol{
var unsplashClient:UnsplashClient {get}
func loadFeed(page:Int,onCompletion: @escaping(([PhotoVM]?, String?) -> Void))
func loadFeedPublisher(page:Int)-> AnyPublisher<[PhotoVM], Error>
func getPhotoDetail(id:String)
func likePhoto(id:String, onCompletion:@escaping(String?)->Void)
func searchPhoto(query:String, page:Int, onCompletion: @escaping(([PhotoVM]?, String?) -> Void))
}
class HomeUseCases:HomeUseCasesProtocol {
var unsplashClient:UnsplashClient
var cancellables = Set<AnyCancellable>()
init(unsplashClient:UnsplashClient){
self.unsplashClient = unsplashClient
}
func loadFeed(page:Int,onCompletion: @escaping(([PhotoVM]?, String?) -> Void)) {
self.unsplashClient.getPhotos(page:page) { (photos, error) in
let photosVM = photos?.compactMap({PhotoVM(photo:$0)})
onCompletion(photosVM,error)
}
}
func loadFeedPublisher(page:Int)-> AnyPublisher<[PhotoVM], Error> {
self.unsplashClient.getPhotos(page: page)
.mapError {return $0}
.map { (photoResponse) -> [PhotoVM] in
let photosVM = photoResponse.photos?.compactMap({PhotoVM(photo:$0)}) ?? []
return photosVM
}.eraseToAnyPublisher()
}
func searchPhoto(query:String, page:Int,onCompletion: @escaping(([PhotoVM]?, String?) -> Void)) {
self.unsplashClient.searchPhoto(query: query, page: page) { (photos, error) in
guard error == nil else {
return
}
let photosVM = photos?.compactMap({PhotoVM(photo:$0)})
onCompletion(photosVM,error)
}
}
func getPhotoDetail(id: String) {
}
func likePhoto(id:String, onCompletion:@escaping(String?)->Void){
self.unsplashClient.likePhoto(id:id){ response in
print(response)
onCompletion(response)
}
}
}
|
//
// UITableViewCell+Extensions.swift
// LoLMyGame
//
// Created by Jack on 2/13/15.
// Copyright (c) 2015 Jackson Jessup. All rights reserved.
//
import Foundation
enum UITableViewCellLolType {
case championData
case matchData
}
extension UITableViewCell {
func createCell(type:UITableViewCellLolType, data:AnyObject) {
var bgColorView = UIView()
bgColorView.backgroundColor = Singleton.UIColorFromHex(0x42C0FB, alpha: 0.6)
bgColorView.layer.masksToBounds = true;
self.selectedBackgroundView = bgColorView;
var smallFont = UIFont(name: "Avenir-Book", size: 13)
var mediumFont = UIFont(name: "Avenir-Book", size: 15)
var bigFont = UIFont(name: "Avenir-Medium", size: 16)
if self.viewWithTag(1) == nil {
// cell needs to be constructed
var viw = UIImageView(frame: CGRectMake(5, 3, self.frame.width - 10, self.frame.height - 6)) as UIView
viw.backgroundColor = Singleton.UIColorFromHex(0x000000, alpha: 0.5)
viw.contentMode = .ScaleAspectFill
viw.clipsToBounds = true
viw.layer.borderWidth = 1
viw.tag = 1
viw.layer.borderColor = Singleton.UIColorFromHex(0xcccccc, alpha: 0.7).CGColor
self.addSubview(viw)
viw = UIView(frame: viw.frame)
viw.backgroundColor = Singleton.UIColorFromHex(0x000000, alpha: 0.2)
self.addSubview(viw)
var colors:[CGColor] = [Singleton.UIColorFromHex(0x000000, alpha: 0.65).CGColor, UIColor.clearColor().CGColor]
var gradient = CAGradientLayer()
gradient.colors = colors
gradient.frame = CGRectMake(0, 0, 170, viw.frame.height)
gradient.startPoint = CGPointMake(0.2, 0.5);
gradient.endPoint = CGPointMake(1.0, 0.5);
viw.layer.insertSublayer(gradient, atIndex:0)
gradient = CAGradientLayer()
gradient.colors = colors.reverse()
gradient.frame = CGRectMake(viw.frame.width-90, 0, 90, viw.frame.height)
gradient.startPoint = CGPointMake(0, 0.5);
gradient.endPoint = CGPointMake(1.0, 0.5);
viw.layer.insertSublayer(gradient, atIndex:0)
var lbl = UILabel()
lbl.textColor = .whiteColor()
lbl.tag = 2
viw.addSubview(lbl)
if type == .championData { // Ranked Data Cells
let stats = data as ChampionStat
lbl.font = bigFont
lbl.frame = CGRectMake(10, 5, lbl.frame.width, lbl.frame.height)
lbl = UILabel()
lbl.tag = 4
lbl.textColor = .whiteColor()
lbl.font = mediumFont
lbl.frame = CGRectMake(10, viw.frame.height - 30, lbl.frame.width, lbl.frame.height)
viw.addSubview(lbl)
var center = CGFloat(viw.frame.height > 100 ? -10 : 0)
lbl = UILabel()
lbl.tag = 5
lbl.frame = CGRectMake(viw.frame.width - 140, (viw.frame.height/2)-30+center, 130, 20)
viw.addSubview(lbl)
lbl = UILabel()
lbl.tag = 6
lbl.frame = CGRectMake(viw.frame.width - 140, (viw.frame.height/2)-10+center, 130, 20)
viw.addSubview(lbl)
lbl = UILabel()
lbl.tag = 7
lbl.frame = CGRectMake(viw.frame.width - 140, (viw.frame.height/2)+10+center, 130, 20)
viw.addSubview(lbl)
if viw.frame.height > 100 {
lbl = UILabel()
lbl.tag = 8
lbl.frame = CGRectMake(viw.frame.width - 140, (viw.frame.height/2)+30+center, 130, 20)
viw.addSubview(lbl)
}
} else { // Recent Match Cells
let stats = data as MatchStat
lbl.font = bigFont
lbl.frame = CGRectMake(10, 5, lbl.frame.width, lbl.frame.height)
lbl = UILabel()
lbl.tag = 3
lbl.frame = CGRectMake(10, viw.frame.height - 30, lbl.frame.width, lbl.frame.height)
viw.addSubview(lbl)
var wl = UIView(frame: CGRectMake(0, 0, 45, 45))
wl.transform = CGAffineTransformMakeRotation( CGFloat(M_PI)/4 )
wl.center = CGPointMake(viw.frame.width, 0)
wl.tag = 4
viw.addSubview(wl)
viw.clipsToBounds = true
}
}
// set the data
if type == .championData {
let stats = data as ChampionStat
(self.viewWithTag(1) as UIImageView).image = Singleton.getArtworkForChamp(stats.id)
var f1 = UIFont(name: "Avenir-Medium", size: 11)
var f2 = UIFont(name: "Avenir-Medium", size: 20)
var attrs : [NSString:AnyObject] = [NSString:AnyObject]()
attrs.updateValue(f1!, forKey: NSFontAttributeName)
attrs.updateValue(UIColor.whiteColor(), forKey: NSForegroundColorAttributeName)
var attrs2 : [NSString:AnyObject] = [NSString:AnyObject]()
attrs2.updateValue(f2!, forKey: NSFontAttributeName)
attrs2.updateValue(UIColor.whiteColor(), forKey: NSForegroundColorAttributeName)
var b = String(stats.totalSessionsWon)
var wl = NSMutableAttributedString(string: String(stats.totalSessionsWon), attributes: attrs2)
wl.appendAttributedString( NSMutableAttributedString(string: " WINS \\ ", attributes: attrs))
wl.appendAttributedString( NSMutableAttributedString(string: String(stats.totalSessionsLost), attributes: attrs2))
wl.appendAttributedString( NSMutableAttributedString(string: " LOSSES ", attributes: attrs))
var lbl = (self.viewWithTag(2) as UILabel)
lbl.text = stats.name
lbl.sizeToFit()
lbl = (self.viewWithTag(4) as UILabel)
lbl.attributedText = wl
lbl.sizeToFit()
var kills = Float(stats.totalChampionKills) / Float(stats.totalSessionsPlayed)
var deaths = Float(stats.totalDeaths) / Float(stats.totalSessionsPlayed)
var assists = Float(stats.totalAssists) / Float(stats.totalSessionsPlayed)
var farm = Float(stats.totalMinionKills) / Float(stats.totalSessionsPlayed)
var paragraphStyle = NSMutableParagraphStyle();
paragraphStyle.alignment = .Right;
attrs = [NSString:AnyObject]()
attrs.updateValue(mediumFont!, forKey: NSFontAttributeName)
attrs.updateValue(UIColor.whiteColor(), forKey: NSForegroundColorAttributeName)
attrs.updateValue(paragraphStyle, forKey: NSParagraphStyleAttributeName)
var avgK = NSMutableAttributedString(string: NSString(format: "%.01f", kills), attributes: attrs)
var avgD = NSMutableAttributedString(string: NSString(format: "%.01f", deaths), attributes: attrs)
var avgA = NSMutableAttributedString(string: NSString(format: "%.01f", assists), attributes: attrs)
var avgCS = NSMutableAttributedString(string: NSString(format: "%.01f", farm), attributes: attrs)
attrs.updateValue(UIFont(name: "Avenir-Medium", size: 18)!, forKey: NSFontAttributeName)
avgK.appendAttributedString( NSMutableAttributedString(string: " K ", attributes: attrs))
avgD.appendAttributedString( NSMutableAttributedString(string: " D ", attributes: attrs))
avgA.appendAttributedString( NSMutableAttributedString(string: " A ", attributes: attrs))
avgCS.appendAttributedString( NSMutableAttributedString(string: " CS", attributes: attrs))
lbl = (self.viewWithTag(5) as UILabel)
lbl.attributedText = avgK
lbl = (self.viewWithTag(6) as UILabel)
lbl.attributedText = avgD
lbl = (self.viewWithTag(7) as UILabel)
lbl.attributedText = avgA
if let l = self.viewWithTag(8) {
(l as UILabel).attributedText = avgCS
}
} else {
let stats = data as MatchStat
(self.viewWithTag(1) as UIImageView).image = Singleton.getArtworkForChamp(String(stats.champID))
smallFont = UIFont(name: "Avenir-Book", size: 13)
mediumFont = UIFont(name: "Avenir-Medium", size: 11)
bigFont = UIFont(name: "Avenir-Medium", size: 20)
let cal = NSCalendar.currentCalendar()
let components = cal.components(.CalendarUnitMinute | .CalendarUnitHour | .CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear, fromDate: stats.date, toDate: NSDate(), options: nil)
var whenStr = "\n"
if components.year > 0 {
whenStr += "\(components.year) year" + (components.year > 1 ? "s":"") + " ago"
} else if components.month > 0 {
whenStr += "\(components.month) month" + (components.month > 1 ? "s":"") + " ago"
} else if components.day > 0 {
whenStr += "\(components.day) day" + (components.day > 1 ? "s":"") + " ago"
} else if components.hour > 0 {
whenStr += "\(components.hour) hour" + (components.hour > 1 ? "s":"") + " ago"
} else {
whenStr += "\(components.minute) minute" + (components.minute > 1 ? "s":"") + " ago"
}
var lbl = (self.viewWithTag(2) as UILabel)
lbl.font = smallFont
lbl.numberOfLines = 2
lbl.text = stats.type + whenStr
lbl.sizeToFit()
var attrs : [NSString:AnyObject] = [NSString:AnyObject]()
attrs.updateValue(mediumFont!, forKey: NSFontAttributeName)
attrs.updateValue(UIColor.whiteColor(), forKey: NSForegroundColorAttributeName)
var attrs2 : [NSString:AnyObject] = [NSString:AnyObject]()
attrs2.updateValue(bigFont!, forKey: NSFontAttributeName)
attrs2.updateValue(UIColor.whiteColor(), forKey: NSForegroundColorAttributeName)
var kda = NSMutableAttributedString(string: NSString(format: "%i", stats.kills), attributes: attrs2)
kda.appendAttributedString( NSMutableAttributedString(string: " KILLS \\ ", attributes: attrs))
kda.appendAttributedString( NSMutableAttributedString(string: NSString(format: "%i", stats.deaths), attributes: attrs2))
kda.appendAttributedString( NSMutableAttributedString(string: " DEATHS \\ ", attributes: attrs))
kda.appendAttributedString( NSMutableAttributedString(string: NSString(format: "%i", stats.assists), attributes: attrs2))
kda.appendAttributedString( NSMutableAttributedString(string: " ASSISTS ", attributes: attrs))
kda.appendAttributedString( NSMutableAttributedString(string: "AS \(stats.getChampName().uppercaseString)", attributes: attrs))
lbl = (self.viewWithTag(3) as UILabel)
lbl.attributedText = kda
lbl.sizeToFit()
var col1 = Singleton.UIColorFromHex(0x5DBB60, alpha: 0.9)
var col2 = Singleton.UIColorFromHex(0xEC5E51, alpha: 0.9)
self.viewWithTag(4)!.backgroundColor = stats.won==true ? col1 : col2
}
}
func createMatchCell() {
}
} |
//
// PropertyMapper.swift
// Modeller
//
// Created by Ericsson on 2016-08-03.
// Copyright © 2016 hedgehoglab. All rights reserved.
//
import Cocoa
import FastEasyMapping
class PropertyMapper: NSObject {
static func propertyMapping() -> FEMMapping {
let mapping = FEMMapping(entityName: "Property")
mapping.addAttributesFromArray(["name", "type"])
mapping.addToManyRelationshipMapping(ParameterMapper.parameterMapping(), forProperty: "parameters", keyPath: "parameters")
//mapping.addRelationshipMapping(ModelMapper.modelMapping(), forProperty: "model", keyPath: "model")
return mapping
}
}
|
//
// DrawerViewController.swift
// Food Aggregator
//
// Created by Chashmeet on 31/10/18.
// Copyright © 2018 Chashmeet Singh. All rights reserved.
//
import UIKit
import MMDrawerController
class DrawerViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let items = ["Dashboard", "Profile", "Your Orders", "Logout"]
let guestItems = ["Dashboard", "Profile", "Login"]
var appDelegate: AppDelegate {
get {
return UIApplication.shared.delegate as! AppDelegate
}
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1.0)
collectionView.register(DrawerCell.self, forCellWithReuseIdentifier: "cell")
collectionView.register(DrawerHeaderCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerView")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
collectionView.reloadData()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let _ = appDelegate.currentUser {
return items.count
} else {
return guestItems.count
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! DrawerCell
if let _ = appDelegate.currentUser {
cell.menuItemLabel.text = items[indexPath.item]
} else {
cell.menuItemLabel.text = guestItems[indexPath.item]
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width: view.frame.width, height: 46)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets.zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: view.frame.width, height: 100)
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionView.elementKindSectionHeader:
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerView", for: indexPath) as! DrawerHeaderCell
view.backgroundColor = UIColor(red: 139.0/255.0, green: 8.0/255.0, blue: 35.0/255.0, alpha: 1.0)
if let user = appDelegate.currentUser {
view.label.text = user.name
} else {
view.label.text = "Guest User"
}
return view
default:
return UICollectionReusableView(frame: CGRect.zero)
}
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let _ = appDelegate.currentUser {
switch indexPath.row {
case 0:
showDashboard()
case 1:
showProfile()
case 2:
showOrders()
case 3:
logoutUser()
default:
break
}
} else {
switch indexPath.row {
case 0:
showDashboard()
case 1:
showProfile()
case 2:
showLogin()
default:
break
}
}
}
func showDashboard() {
if let _ = navigationController?.topViewController as? ClientHomeViewController {
closeDrawer()
} else {
let nvc = appDelegate.centerContainer?.centerViewController as! UINavigationController
let homeViewController = ClientHomeViewController()
nvc.pushViewController(homeViewController, animated: true)
appDelegate.centerContainer?.closeDrawer(animated: true, completion: nil)
}
}
func showProfile() {
if let _ = navigationController?.topViewController as? ProfileViewController {
closeDrawer()
} else {
let nvc = appDelegate.centerContainer?.centerViewController as! UINavigationController
let profileViewController = ProfileViewController()
nvc.pushViewController(profileViewController, animated: true)
appDelegate.centerContainer?.closeDrawer(animated: true, completion: nil)
}
}
func showLogin() {
if let _ = navigationController?.topViewController as? LoginViewController {
closeDrawer()
} else {
let nvc = appDelegate.centerContainer?.centerViewController as! UINavigationController
let loginVC = LoginViewController()
loginVC.fromSignUpView = true
nvc.pushViewController(loginVC, animated: true)
appDelegate.centerContainer?.closeDrawer(animated: true, completion: nil)
}
}
func closeDrawer() {
appDelegate.centerContainer?.closeDrawer(animated: true, completion: nil)
}
func logoutUser() {
if let user = appDelegate.currentUser {
let params = [
Client.Keys.Email: user.emailID,
Client.Keys.Token: user.accessToken
]
Client.sharedInstance.logoutUser(params as [String : AnyObject]) { (_, success, error) in
DispatchQueue.main.async {
if success {
self.appDelegate.centerContainer?.dismiss(animated: true, completion: nil)
}
}
}
} else {
self.appDelegate.centerContainer?.dismiss(animated: true, completion: nil)
}
}
func showOrders() {
if let _ = navigationController?.topViewController as? OrdersViewController {
closeDrawer()
} else {
let nvc = appDelegate.centerContainer?.centerViewController as! UINavigationController
let orderController = OrdersViewController(collectionViewLayout: UICollectionViewFlowLayout())
nvc.pushViewController(orderController, animated: true)
appDelegate.centerContainer?.closeDrawer(animated: true, completion: nil)
}
}
}
|
//
// LoginController.swift
// companion
//
// Created by Uchenna Aguocha on 9/27/18.
// Copyright © 2018 Yves Songolo. All rights reserved.
//
import Foundation
import UIKit
import NVActivityIndicatorView
import AuthenticationServices
import SafariServices
class LoginController: UIViewController {
// MARK: - Properties
var user: User?
var activityIndicator = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50), type: .ballPulseSync, color: .gloomyBlue, padding: 0)
// MARK: - UI Elements
let customAlertView: CustomAlertView = {
let view = CustomAlertView()
return view
}()
private let companionLabel: UILabel = {
let label = UILabel()
label.text = "Welcome to Companion!"
label.textAlignment = .left
label.font = UIFont.init(name: "AvenirNext-DemiBold", size: 33)
label.numberOfLines = 2
label.textColor = MakeSchoolDesignColor.black
return label
}()
private let emailTextField: UITextField = {
// MARK: TODO - Add padding to the image
let textField = LeftPaddedTextField()
textField.leftViewMode = .always
textField.textColor = MakeSchoolDesignColor.darkBlue
textField.layer.cornerRadius = 6
textField.layer.shadowColor = #colorLiteral(red: 0.03137254902, green: 0.4862745098, blue: 0.7215686275, alpha: 1).cgColor
textField.layer.shadowOffset = CGSize.zero
textField.layer.shadowOpacity = 0.40
textField.layer.shadowRadius = 5
textField.attributedPlaceholder = NSAttributedString(string: "Make School Email", attributes: [NSAttributedStringKey.foregroundColor: MakeSchoolDesignColor.darkBlue])
textField.textAlignment = .left
textField.font = UIFont(name: "AvenirNext-DemiBold", size: 17)
textField.becomeFirstResponder()
textField.isUserInteractionEnabled = true
textField.autocapitalizationType = UITextAutocapitalizationType.none
textField.backgroundColor = MakeSchoolDesignColor.faintBlue
return textField
}()
private let passwordTextField: UITextField = {
// MARK: TODO - Uchenna Add padding to the image
// let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
// leftView.backgroundColor = MakeSchoolDesignColor.faintBlue
//
// let imageView = UIImageView(frame: CGRect(x: 10, y: 0, width: 24, height: 24))
// imageView.image = #imageLiteral(resourceName: "lock").withRenderingMode(.alwaysTemplate)
// imageView.tintColor = MakeSchoolDesignColor.darkBlue
//
// leftView.addSubview(imageView)
let textField = LeftPaddedTextField()
textField.leftViewMode = .always
textField.textAlignment = .left
textField.textColor = MakeSchoolDesignColor.darkBlue
textField.backgroundColor = MakeSchoolDesignColor.faintBlue
textField.layer.cornerRadius = 6
textField.layer.shadowColor = #colorLiteral(red: 0.03137254902, green: 0.4862745098, blue: 0.7215686275, alpha: 1).cgColor
textField.layer.shadowOffset = CGSize.zero
textField.layer.shadowOpacity = 0.40
textField.layer.shadowRadius = 5
textField.autocapitalizationType = UITextAutocapitalizationType.none
textField.attributedPlaceholder = NSAttributedString(string: "Make School Password", attributes: [NSAttributedStringKey.foregroundColor: MakeSchoolDesignColor.darkBlue])
textField.font = UIFont(name: "AvenirNext-DemiBold", size: 17)
textField.isSecureTextEntry = true
return textField
}()
private var loginButton: UIButton = {
let button = UIButton()
button.setTitle("Login", for: .normal)
button.setTitleColor(MakeSchoolDesignColor.faintBlue, for: .normal)
button.backgroundColor = MakeSchoolDesignColor.darkBlue
button.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 17)
button.layer.cornerRadius = 6
button.addTarget(self, action: #selector(handleLogin), for: .touchUpInside)
return button
}()
private var facebookLoginButton: UIButton = {
let button = UIButton()
button.setTitle("Login with Facebook", for: .normal)
button.setTitleColor(MakeSchoolDesignColor.faintBlue, for: .normal)
button.backgroundColor = UIColor(r: 59, g: 89, b: 152, a: 1)
button.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 17)
button.layer.cornerRadius = 6
button.addTarget(self, action: #selector(handleFacebookLogin), for: .touchUpInside)
return button
}()
// MARK: - View Life Cycle Methods
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = MakeSchoolDesignColor.faintBlue
setupAutoLayout()
emailTextField.delegate = self
emailTextField.becomeFirstResponder()
passwordTextField.delegate = self
self.hideKeyboardWhenTappedAround()
}
// MARK: - Methods
private func setupAutoLayout() {
// Add Contraints to each subview
emailTextField.anchor(top: nil, right: nil, bottom: nil, left: nil, topPadding: 0, rightPadding: 0, bottomPadding: 0, leftPadding: 0, height: 60, width: 300)
passwordTextField.anchor(top: nil, right: nil, bottom: nil, left: nil, topPadding: 0, rightPadding: 0, bottomPadding: 0, leftPadding: 0, height: 60, width: 300)
let textFieldStackView = UIStackView(arrangedSubviews: [emailTextField, passwordTextField])
textFieldStackView.alignment = .center
textFieldStackView.distribution = .equalSpacing
textFieldStackView.axis = .vertical
textFieldStackView.spacing = 16
view.addSubviews(views: companionLabel, textFieldStackView, loginButton, facebookLoginButton)
companionLabel.anchor(
top: view.safeAreaLayoutGuide.topAnchor,
right: view.safeAreaLayoutGuide.rightAnchor,
bottom: nil,
left: view.safeAreaLayoutGuide.leftAnchor,
topPadding: 50,
rightPadding: 73,
bottomPadding: 0,
leftPadding: 36,
height: 100,
width: 0)
textFieldStackView.anchor(
centerX: view.centerXAnchor,
centerY: view.centerYAnchor,
top: nil,
right: view.safeAreaLayoutGuide.rightAnchor,
bottom: nil,
left: view.safeAreaLayoutGuide.leftAnchor,
topPadding: 40,
rightPadding: 0,
bottomPadding: 0,
leftPadding: 0,
height: 177,
width: 0)
loginButton.anchor(
centerX: view.centerXAnchor,
centerY: nil,
top: textFieldStackView.bottomAnchor,
right: nil,
bottom: nil,
left: nil,
topPadding: 42,
rightPadding: 0,
bottomPadding: 0,
leftPadding: 0,
height: 46,
width: 206)
facebookLoginButton.anchor(
centerX: view.centerXAnchor,
centerY: nil,
top: loginButton.bottomAnchor,
right: nil,
bottom: nil,
left: nil,
topPadding: 30,
rightPadding: 0,
bottomPadding: 0,
leftPadding: 0,
height: 46,
width: 206)
}
// Sets up the positions and adds the activity indicator on the screen
private func configureActivityIndicator() {
Constants.indicatorView = NVActivityIndicatorView(frame: CGRect(x: view.frame.midX, y: view.frame.midY, width: view.frame.width/8, height: view.frame.height/8), type: .lineScale, color: .gloomyBlue, padding: 0)
Constants.indicatorView.center = view.center
view.addSubview(Constants.indicatorView)
Constants.indicatorView.startAnimating()
}
// MARK: Methods with @objc
@objc private func handleLogin() {
// After logging in, present the MainTabBarController
guard let email = emailTextField.text,
let password = passwordTextField.text
else { return }
configureActivityIndicator()
UserServices.login(email: email, password: password) { (user) in
self.activityIndicator.stopAnimating()
if let user = user as? User {
// handle existing user
User.setCurrent(user, writeToUserDefaults: true)
DispatchQueue.main.async {
let mainTabBarController = MainTabBarController()
self.view.window?.rootViewController = mainTabBarController
self.view.window?.makeKeyAndVisible()
}
} else {
self.activityIndicator.stopAnimating()
self.customAlertView.show(animated: true)
DispatchQueue.main.async {
Constants.indicatorView.stopAnimating()
self.presentAlert(title: "Bad credentails", message: "Incorrect email or password. Please try again.")
}
}
}
}
@objc private func handleFacebookLogin() {
print("LOGIN WITH FACEBOOK")
let defaults = UserDefaults.standard
let initialViewController: UIViewController
if let _ = User.current,
let userData = defaults.object(forKey: Constants.current) as? Data,
let user = try? JSONDecoder().decode(User.self, from: userData) {
User.setCurrent(user, writeToUserDefaults: true)
initialViewController = MainTabBarController()
view.window?.rootViewController = initialViewController
view.window?.makeKeyAndVisible()
} else {
// let navController = UINavigationController(rootViewController: FacebookLoginWebViewController())
let facebookVC = FacebookLoginWebViewController()
facebookVC.modalPresentationStyle = .currentContext
self.present(facebookVC, animated: true, completion: nil)
}
}
}
extension LoginController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
print("show keyboard")
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
//
// ConfettiViewController.swift
// OpenSourceFrameworks
//
// Created by Ayush Verma on 17/05/18.
// Copyright © 2018 Ayush Verma. All rights reserved.
//
import UIKit
import SAConfettiView
class ConfettiViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.confetti()
// to keep the speed of the particles less but to increase the number use following.
// for _ in 0...3{
// self.confetti()
// }
}
func confetti(){
let confettiView = SAConfettiView(frame: self.view.bounds)
self.view.addSubview(confettiView)
confettiView.type = .Diamond
confettiView.colors = [UIColor.red, UIColor.green, UIColor.blue]
confettiView.intensity = 1.0
confettiView.startConfetti()
}
//eoc
}
|
//
// InmoovBasicController.swift
// CosRemote
//
// Created by 郭 又鋼 on 2016/3/7.
// Copyright © 2016年 郭 又鋼. All rights reserved.
//
import Foundation
import UIKit
class InmoovBasicController: UIViewController {
@IBOutlet var slArm: UISlider!
@IBOutlet var slIndex: UISlider!
@IBOutlet var slMiddle: UISlider!
@IBOutlet var slRing: UISlider!
@IBOutlet var slLittle: UISlider!
@IBOutlet var slThumb: UISlider!
var servoArr:[UISlider] = []
var sliderThread:NSThread?
var sliderBuffer = [Int: Int]() ;
override func viewWillAppear(animated: Bool) {
self.navigationItem.title = ""
let right = UIBarButtonItem(title: "Inmoov", style: UIBarButtonItemStyle.Done, target: self, action: #selector(InmoovBasicController.inmoonUrlPress)) ;
self.navigationItem.rightBarButtonItem = right ;
servoArr = [slArm, slIndex, slMiddle, slRing, slLittle, slThumb ] ;
for slider in servoArr {
slider.addTarget(self, action: #selector(InmoovBasicController.onSlideChange(_:)), forControlEvents: UIControlEvents.ValueChanged)
}
}
func onSlideChange( sender:UISlider ) {
print("slide valu = \( sender.value )")
var sliderIndex = -1 ;
for (index, slider) in servoArr.enumerate() {
if slider == sender {
//print("find sender = \( index ) ")
sliderIndex = index ;
}
}
if ( sliderIndex != -1 ) {
sliderBuffer[sliderIndex] = Int(sender.value)
if let remote = Common.global.cosRemote {
remote.setFinger(sliderIndex, degree: Int(sender.value) )
}
/*
if sliderThread == nil {
sliderThread = NSThread(target: self, selector: "run", object: nil);
}
*/
}
}
func run() {
while sliderBuffer.count > 0 {
if let remote = Common.global.cosRemote {
print(remote)
}
}
}
func inmoonUrlPress() {
UIApplication.sharedApplication().openURL(NSURL(string: "http://inmoov.fr/")! );
}
@IBAction func btnAllZeroPress(sender: AnyObject) {
if let remote = Common.global.cosRemote {
remote.setAllServo(0) ;
}
}
@IBAction func btnAll180Press(sender: AnyObject) {
if let remote = Common.global.cosRemote {
remote.setAllServo(180) ;
}
}
@IBAction func btnFingerZeroPress(sender: AnyObject) {
if let remote = Common.global.cosRemote {
remote.setAllFinger(0)
}
}
@IBAction func btnFinger90Press(sender: AnyObject) {
if let remote = Common.global.cosRemote {
remote.setAllFinger(90)
}
}
@IBAction func btnFinger45Press(sender: AnyObject) {
if let remote = Common.global.cosRemote {
remote.setAllFinger(45)
}
}
@IBAction func btnFinger180Press(sender: AnyObject) {
if let remote = Common.global.cosRemote {
remote.setAllFinger(180)
}
}
} |
//
// Constants.swift
// Bring It!
//
// Created by Administrador on 10/25/17.
// Copyright © 2017 tec. All rights reserved.
//
import Foundation
/*
//EndPoints para los Usuarios
api.post('/saveUser',userCtrl.saveUser)
api.post('/loginSocialNetwork',userCtrl.loginSocialNetwork)
api.post('/authenticate',userCtrl.signIn)
api.get('/getUsers',userCtrl.getUsers)
//EndPoints para los productos
api.post('/saveProduct',productCtrl.saveProduct)
api.delete('/deleteProduct/:idProduct', productCtrl.deleteProduct)
api.put('/updateProduct/:idProduct',productCtrl.updateProduct)
api.put('/updateStateProduct',productCtrl.updateStateProduct)
//EndPoints para listas de compras
api.post('/saveShopList',shopListCtrl.saveShopList)
api.get('/getShopLists',shopListCtrl.getShopLists)
api.get('/getShopListsUser/:idUser', shopListCtrl.getShopListUser)
api.delete('/deleteShopList/:idShopList', shopListCtrl.deleteShopList)
api.put('/updateShopList/:idShopList',shopListCtrl.updateShopList)
api.post('/shareShopList',shopListCtrl.updateShopListArrayUsers)
*/
class Constants {
//Rest service
static var URL = "https://listas-comprasb.herokuapp.com/"
static var POSTSOCIALNETWORK = "loginSocialNetwork/"
static var POSTUSER = "saveUser/"
static var POSTSHOPPINGLIST = "saveShopList/"
static var POSTPRODUCT = "saveProduct/"
static var GETUSERSHOPPINGLIST = "getShopListsUser/"
static var GETUSER = "getUser/"
static var USERAUTHENTICATE = "authenticate/"
static var SHOPPINGLIST_USER = "getShopLists/"
static var DELETEPRODUCT = "deleteProduct/"
static var DELETESHOPPINGLIST = "deleteShopList/"
static var SHARESHOPPINGLIST = "shareShopList/"
static var UPDATESHOPPINGLIST = "updateShopList/"
static var UPDATEPRODUCT = "updateProduct/"
static var ARRAYNUMBERS = [Number(number:"1", numberLetter:"Un"),
Number(number:"1", numberLetter:"Uno"),
Number(number:"2", numberLetter:"Dos"),
Number(number:"3", numberLetter:"Tres"),
Number(number:"4", numberLetter:"Cuatro"),
Number(number:"5", numberLetter:"Cinco"),
Number(number:"6", numberLetter:"Seis"),
Number(number:"7", numberLetter:"Siete"),
Number(number:"8", numberLetter:"Ocho"),
Number(number:"9", numberLetter:"Nueve"),
Number(number:"10", numberLetter:"Diez"),
Number(number:"11", numberLetter:"Once"),
Number(number:"12", numberLetter:"Doce"),
Number(number:"13", numberLetter:"Trece"),
Number(number:"14", numberLetter:"Catorce"),
Number(number:"15", numberLetter:"15"),
Number(number:"16", numberLetter:"16"),
Number(number:"17", numberLetter:"17"),
Number(number:"18", numberLetter:"18"),
Number(number:"19", numberLetter:"19"),
Number(number:"20", numberLetter:"20")
]
//Regular expression to validate the user email input
/*
static var PATTERN_EMAIL = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*$";
*/
static var PATTERN_EMAIL = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
static var PATTERN_PASSWORD = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)([A-Za-z\\d]){8,12}$"
static var STATUS_OK: Int = 200
}
|
//
// Compositor.swift
// Whale
//
// Created by Eliel A. Gordon on 3/24/17.
// Copyright © 2017 Eliel A. Gordon. All rights reserved.
//
import Foundation
import AVFoundation
import Result
import Photos
import AssetsLibrary
enum CompositorError: Error {
case couldNotExport
}
struct Compositor {
var storageURL: URL {
return FileManager.default.temporaryDirectory
}
var tempFileName: String {
return UUID().uuidString
}
var mixComposition: AVMutableComposition
init(urls: [URL]) {
let assets = urls.map {AVAsset(url: $0)}
let composition = AVMutableComposition()
self.mixComposition = Compositor.addTracks(assets: assets, composition: composition)
}
static func addTracks(assets: [AVAsset], composition: AVMutableComposition) -> AVMutableComposition {
let videoTrack = composition.addMutableTrack(
withMediaType: AVMediaTypeVideo,
preferredTrackID: kCMPersistentTrackID_Invalid
)
let audioTrack = composition.addMutableTrack(
withMediaType: AVMediaTypeAudio,
preferredTrackID: kCMPersistentTrackID_Invalid
)
var totalDuration = kCMTimeZero
assets.forEach { (asset) in
do {
try videoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, asset.duration),
of: asset.tracks(withMediaType: AVMediaTypeVideo)[0],
at: totalDuration)
try audioTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, asset.duration),
of: asset.tracks(withMediaType: AVMediaTypeAudio)[0] ,
at: totalDuration)
totalDuration = CMTimeAdd(totalDuration, asset.duration)
} catch let error {
fatalError("Error: \(error.localizedDescription)")
}
}
// Need to rotate video because AVFoundation records in landscape
videoTrack.preferredTransform = CGAffineTransform(rotationAngle: .pi / 2)
return composition
}
/*
Exports an asset to the export url
*/
func export(asset: AVAsset, completion: @escaping (Result<URL, CompositorError>) -> Void) {
let exporter = AVAssetExportSession(
asset: asset,
presetName: AVAssetExportPresetHighestQuality
)
exporter?.outputURL = storageURL
.appendingPathComponent(tempFileName)
.appendingPathExtension("mov")
exporter?.outputFileType = AVFileTypeQuickTimeMovie
exporter?.shouldOptimizeForNetworkUse = true
exporter?.exportAsynchronously {
DispatchQueue.main.async {
guard let exportUrl = exporter?.outputURL else {return completion(.failure(CompositorError.couldNotExport))}
completion(.success(exportUrl))
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.