text stringlengths 8 1.32M |
|---|
//
// Splash.swift
// PalmTree
//
// Created by SprintSols on 3/7/20.
// Copyright © 2020 apple. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
import CoreLocation
class LocationVC: UIViewController, CLLocationManagerDelegate
{
//MARK:- Properties
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var lblHeading: UILabel!
@IBOutlet weak var lblLocation: UILabel!
@IBOutlet weak var lblDistance: UILabel!
@IBOutlet weak var lblType: UILabel!
@IBOutlet weak var locView: UIView!
var locationManager = CLLocationManager()
lazy var geocoder = CLGeocoder()
//MARK:- Cycle
override func viewDidLoad() {
super.viewDidLoad()
locView.layer.cornerRadius = 5.0
if userDetail?.locationName != ""
{
lblLocation.text = userDetail?.locationName
}
if (CLLocationManager.locationServicesEnabled())
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@IBAction func backBtnACtion(_ sender: Any)
{
self.navigationController?.popViewController(animated: true)
}
@IBAction func locBtnAction(_ sender: Any)
{
locView.alpha = 1
//Location manager
locationManager.startUpdatingLocation()
}
@IBAction func cancelBtnAction(_ sender: Any)
{
locView.alpha = 0
}
//MARK:- Cutom Functions
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let currentLoc = locations.last{
userDetail?.currentLocation = currentLoc
userDetail?.lat = currentLoc.coordinate.latitude
userDetail?.lng = currentLoc.coordinate.longitude
defaults.set(userDetail?.lat, forKey: "latitude")
defaults.set(userDetail?.lng, forKey: "longitude")
print("Latitude: \(currentLoc.coordinate.latitude)")
print("Longitude: \(currentLoc.coordinate.longitude)")
geocoder.reverseGeocodeLocation(currentLoc) { (placemarks, error) in
self.processResponse(withPlacemarks: placemarks, error: error)
}
}
}
private func processResponse(withPlacemarks placemarks: [CLPlacemark]?, error: Error?) {
// Update View
if let error = error
{
print("Unable to Reverse Geocode Location (\(error))")
}
else
{
if let placemarks = placemarks, let placemark = placemarks.first
{
print("Name: \(placemark.name)")
print("locality: \(placemark.locality)")
print("subLocality: \(placemark.subLocality)")
print("administrativeArea: \(placemark.administrativeArea)")
print("country: \(placemark.country)")
userDetail?.currentAddress = placemark.compactAddress ?? ""
userDetail?.locationName = placemark.locationName ?? ""
userDetail?.country = placemark.currentCountry ?? ""
defaults.set(userDetail?.currentAddress, forKey: "address")
defaults.set(userDetail?.locationName, forKey: "locName")
defaults.set(userDetail?.country, forKey: "country")
locationManager.stopUpdatingLocation()
self.navigationController?.popViewController(animated: true)
}
}
}
}
|
//
// DateTransformer.swift
// Long Box
//
// Created by Frank Michael on 10/19/14.
// Copyright (c) 2014 Frank Michael Sanchez. All rights reserved.
//
import Foundation
class DateTransformer: NSValueTransformer {
override func transformedValue(value: AnyObject?) -> AnyObject? {
let date = value as NSDate
var df = NSDateFormatter()
df.dateFormat = "MM/yyyy"
return df.stringFromDate(date)
}
} |
//
// DemodulateWFM.swift
// SimpleSDR3
//
// https://en.wikipedia.org/wiki/FM_broadcasting#Technology
// https://www.law.cornell.edu/cfr/text/47/73.310
//
// Created by Andy Hooper on 2020-02-26.
// Copyright © 2020 Andy Hooper. All rights reserved.
//
import SimpleSDRLibrary
class DemodulateWFM:DemodulateAudio {
static let FREQUENCY_DEVIATION = 75000, //TODO configurable at init
DEEMPHASIS_TIME = Float(75e-6)
var pilotDetect: AutoGainControl<RealSamples>?
init<S:SourceProtocol>(source:S)
where S.Output == ComplexSamples {
super.init("DemodulateWFM")
let sourceSampleHz = Int(source.sampleFrequency())
let WFM_SAMPLE_HZ = 200000,
WFM_FILTER_HZ = DemodulateWFM.FREQUENCY_DEVIATION
let downSampleIF = UpFIRDown(source:source,
WFM_SAMPLE_HZ,
sourceSampleHz,
15, // * 10 * 2
Float(WFM_FILTER_HZ) / Float(WFM_SAMPLE_HZ),
windowFunction:FIRKernel.blackman) // kaiser(5.0f));
let demodulated = FMDemodulate(source:downSampleIF,
modulationFactor: 0.5) //(WFM_FREQUENCY_DEVIATION / WFM_SAMPLE_HZ));
let PILOT_CENTRE_HZ = Float(19000)
let pilotPeak = FIRKernel.peak(filterSemiLength: 29,
normalizedPeakFrequency: Float(PILOT_CENTRE_HZ) / Float(WFM_SAMPLE_HZ),
stopBandAttenuation: 60)
//FIRKernel.plotFrequencyResponse(pilotPeak, title: "FM Pilot Filter")
let pilotFilter = FIRFilter(source:demodulated,
pilotPeak)
// let pilotFilter = Goertzel(source:demodulated, targetFrequencyHz:PILOT_CENTRE_HZ, Nfft: 200)
pilotDetect = AutoGainControl(source:pilotFilter)
let audioSampleHz = Int(audioOut.sampleFrequency()),
AUDIO_FILTER_HZ = 15000
let downSampleAF = UpFIRDown(source:demodulated,
audioSampleHz,
WFM_SAMPLE_HZ,
15, // * 25 * 2
Float(AUDIO_FILTER_HZ) / Float(audioSampleHz),
windowFunction:FIRKernel.blackman) // kaiser(5.0f));
let deemphasis = FMDeemphasis(source: downSampleAF,
tau: DemodulateWFM.DEEMPHASIS_TIME)
let audioDC = DCRemove(source:deemphasis, 64)
let audioAGC = AutoGainControl(source:audioDC)
audioOut.setSource(source:audioAGC)
//let spectrumSource = downSampleIF
//let spectrumSource = RealToComplex(source: demodulated)
let spectrumSource = RealToComplex(source:downSampleAF)
//let spectrumSource = RealToComplex(source: audioAGC)
spectrum.setSource(spectrumSource)
scope.setSource(audioAGC)
}
}
|
//
// PromiseCoordinator.swift
// MinervaExample
//
// Copyright © 2019 Optimize Fitness, Inc. All rights reserved.
//
import Foundation
import UIKit
import Minerva
public class PromiseCoordinator<T: PromiseDataSource, U: ViewController>: MainCoordinator<T, U>, DataSourceUpdateDelegate {
public typealias RefreshBlock = (_ dataSource: T, _ animated: Bool) -> Void
public var refreshBlock: RefreshBlock?
public override init(navigator: Navigator, viewController: U, dataSource: T) {
super.init(navigator: navigator, viewController: viewController, dataSource: dataSource)
dataSource.updateDelegate = self
}
// MARK: - DataSourceUpdateDelegate
public func dataSource(_ dataSource: DataSource, encountered error: Error) {
viewController.alert(error, title: "Failed to load your data")
}
public func dataSource(
_ dataSource: DataSource,
update sections: [ListSection],
animated: Bool,
completion: DataSourceUpdateDelegate.Completion?
) {
listController.update(with: sections, animated: animated, completion: completion)
}
public func dataSourceStartedUpdate(_ dataSource: DataSource) {
LoadingHUD.show(in: viewController.view)
}
public func dataSourceCompletedUpdate(_ dataSource: DataSource) {
LoadingHUD.hide(from: viewController.view)
}
// MARK: - ViewControllerDelegate
override public func viewController(_ viewController: ViewController, viewWillAppear animated: Bool) {
super.viewController(viewController, viewWillAppear: animated)
refreshBlock?(dataSource, animated)
}
}
|
//
// Plot.swift
// Decision
//
// Created by Yuri Chervonyi on 3/14/19.
// Copyright © 2019 CHRGames. All rights reserved.
//
import Foundation
class Plot {
static let instance = Plot()
private(set) var vault: [String : Stage]!
static let FIRST_STAGE = "AA000"
private var _startStage: String?
var startStage: String {
get {
return _startStage ?? Plot.FIRST_STAGE
}
set {
_startStage = newValue
}
}
private(set) var lastStageId: String! = Plot.FIRST_STAGE
func loadXMLFiles() {
vault = PlotXMLParser.loadPlotFromXML()
loadScenario()
}
func loadScenario() {
var selectedLanguage: String!
switch Settings.language {
case Settings.Language.ENGLISH: selectedLanguage = "scenario_en"
case .RUSSIAN: selectedLanguage = "scenario_ru"
case .UKRAINIAN: selectedLanguage = "scenario_uk"
}
vault = ScenarioXMLParser.loadScenario(baseOn: vault, in: selectedLanguage)
}
func getStage(by id: String) -> Stage {
lastStageId = id
Settings.lastStage = id
return vault[id] ?? Stage()
}
func lookAtNextStage(by id: String) -> Stage {
return vault[id] ?? Stage()
}
func getActiveStage() -> Stage {
return getStage(by: lastStageId)
}
func restart() {
lastStageId = Plot.FIRST_STAGE
}
private init() { }
}
|
//
// DetailsPresenter.swift
// NTGTags
//
// Created by Mena Gamal on 2/16/20.
// Copyright © 2020 Mena Gamal. All rights reserved.
//
import Foundation
import UIKit
protocol DetailsPresenterDelegate {
}
class DetailsPresenter: DetailsPresenterDelegate{
//private var cachedObj:ArrayOfCachedModule!
private var interactor:DetailsInteractor?
private var router:DetailsRouter?
//MARK: TO AVOID RETAIN CYCLE
private weak var view:DetailsView?
var character:Results
private var comicsDataSource:DetailsCellDataSource!
private var seriesDataSource:DetailsCellDataSource!
private var storiesDataSource:DetailsCellDataSource!
private var eventsDataSource:DetailsCellDataSource!
init(interactor:DetailsInteractor,router:DetailsRouter,view:DetailsView,character:Results) {
self.interactor = interactor
self.router = router
self.view = view
self.character = character
}
func loadDetailsLayout() {
if self.character.characterImageBaseString != nil {
let dataDecoded : Data = Data(base64Encoded: character.characterImageBaseString, options: .ignoreUnknownCharacters)!
let decodedimage:UIImage = UIImage(data: dataDecoded)!
self.view?.mainImageView.image = decodedimage
} else {
self.view?.mainImageView.setImageWithUrl(url: character.resourceURI!)
}
self.view?.labelName.text = self.character.name
self.view?.labelDesc.text = self.character.descriptionStr
// MARK: MARVEL APU ISSUE
// marvel doesn't send the url of the comic , event , stories or series
// it require a new API call for each item which is Totaly wrong .!!!!!!!!!!!!!!!!!!!!
let url = "\(character.thumbnail!.path!).\(character.thumbnail!.extensionStr!)"
self.comicsDataSource = DetailsCellDataSource(collection: self.view!.comicsCollection, items: self.character.comics!.items!,img:url)
self.seriesDataSource = DetailsCellDataSource(collection: self.view!.seriesCollection, items: self.character.series!.items!,img:url)
self.storiesDataSource = DetailsCellDataSource(collection: self.view!.storiesCollection, items: self.character.stories!.items!,img:url)
self.eventsDataSource = DetailsCellDataSource(collection: self.view!.eventsCollection, items: self.character.events!.items!,img:url)
}
}
|
import Foundation
import Runtime
func resolveArguments(for value: Any, using type: Any.Type, isNil: Bool = false) throws -> [FunctionArgument] {
if let type = type as? MethodCallResolvable.Type {
return try type.arguments(value: value, isNil: isNil)
}
let (kind, genericTypes, properties) = try typeInfo(of: type, .kind, .genericTypes, .properties)
switch kind {
case .class:
if isNil {
return [.int(.int(0))]
}
return [.int(.pointer(Unmanaged.passUnretained(value as AnyObject).toOpaque()))]
case .optional:
let actualType = genericTypes.first!
let isNil = try isNil || isValueNil(value: value, type: actualType)
if let actualType = actualType as? MethodCallResolvable.Type, actualType.hasExtraInhabitants {
return try actualType.arguments(value: value, isNil: isNil)
}
let kind = try typeInfo(of: actualType, .kind)
if kind == .class {
return try resolveArguments(for: value, using: actualType, isNil: isNil)
}
return try resolveArguments(for: value, using: actualType, isNil: isNil).map { $0.intArgument() } + [.int(.int8(isNil ? 1 : 0))]
case .enum:
if isNil {
return [.int(.int8(0))]
}
return [.int(.int8(withUnsafeBytes(of: value) { $0.bindMemory(to: Int8.self).baseAddress!.pointee }))]
default:
return try properties.flatMap { try resolveArguments(for: isNil ? 0 : $0.get(from: value), using: $0.type, isNil: isNil) }
}
}
|
//
// StyleManager.swift
// Quizzical
//
// Created by Casey Conway on 4/29/19.
// Copyright © 2019 Casey Conway. All rights reserved.
//
//ABOUT - This file includes all the color settings for the app
import UIKit
struct StyleManager {
//Colors for result text field when right or wrong answer selected
static let correctColor = UIColor(red: 65.0/255, green: 145.0/255, blue: 135.0/255, alpha: 1.0)
static let wrongColor = UIColor(red: 242.0/255, green: 166.0/255, blue: 110.0/255, alpha: 1.0)
//Enabled/Disabled Button Color Settings
static let enabledButtonBackgroundColor: UIColor = UIColor(red: 54/255.0, green: 119/255.0, blue: 147/255.0, alpha: 1.0)
static let disabledButtonBackgroundColor: UIColor = UIColor(red: 54/255.0, green: 119/255.0, blue: 147/255.0, alpha: 0.5)
static let enabledButtonTextColor: UIColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
static let disabledButtonTextColor: UIColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.4)
}
|
//
// EntityJsonDecoderTests.swift
// CoreDataJsonParserTests
//
// Created by Alex Belozierov on 9/23/19.
// Copyright © 2019 Alex Belozierov. All rights reserved.
//
import XCTest
import CoreData
@testable import CoreDataJsonParser
class EntityJsonDecoderTests: XCTestCase {
func testJsonDecodersFuncs() {
let json = Json.test[0]!.media[0]!
performAndWaitOnViewContext { context in
var decoder = Media.sharedJsonDecoder.entityDecoder
do {
let media = try json.decode(type: Media.self, context: context)
let media2 = try decoder.findObject(json: json, context: context)
XCTAssertEqual(media, media2)
let media3 = try decoder.create(json: json, context: context)
context.delete(media3)
XCTAssertNotEqual(media, media3)
let predicate = try decoder.predicate(json: json)!
let media4 = try decoder.findObject(predicate: predicate, context: context)
XCTAssertEqual(media, media4)
let media5 = try decoder.parse(json: json, context: context, predicate: predicate)
XCTAssertEqual(media, media5)
decoder.entityModel.findObjectStrategy = .predicate { _ in
NSPredicate(format: "SELF = %@", media)
}
let media6 = try decoder.findObject(json: json, context: context)
XCTAssertEqual(media, media6)
decoder.entityModel.findObjectStrategy = .none
XCTAssertNil(try decoder.findObject(json: json, context: context))
} catch {
XCTFail(error.localizedDescription)
}
}
}
func testJsonParsing() {
let json = Json.test
let isoFormatter = ISO8601DateFormatter.standart
performAndWaitOnViewContext { context in
do {
let start = Date()
let posts = try json.decode(type: [Post].self, context: context)
print("TIME", Date().timeIntervalSince(start))
XCTAssertEqual(posts.count, json.array?.count)
//test post parse
let post = posts[0]
let postJson = json.array?.first
XCTAssertEqual(post.body, postJson?.body)
XCTAssertEqual(post.commentsCount, postJson?.commentsCount)
XCTAssertEqual(post.createdDate, postJson?.createdDate.map(isoFormatter.date))
XCTAssertEqual(post.id, postJson?.id)
XCTAssertEqual(post.isAdvertisable, postJson?.isAdvertisable)
XCTAssertEqual(post.isAdvertised, postJson?.isAdvertised)
XCTAssertEqual(post.isContentUnavailable, postJson?.isContentUnavailable)
XCTAssertEqual(post.isLiked, postJson?.isLiked)
XCTAssertEqual(post.lastModifiedDate, postJson?.lastModifiedDate.map(isoFormatter.date))
XCTAssertEqual(post.reactionsCount, postJson?.reactionsCount)
XCTAssertEqual(post.sharesCount, postJson?.sharesCount)
//test media parse
let media = (post.media?.allObjects as? [Media])![0]
let mediaJson = postJson!.media![0]!
XCTAssertEqual(media.advertised, mediaJson.advertised)
XCTAssertEqual(media.content, mediaJson.content)
XCTAssertEqual(media.createdDate, mediaJson.lastModifiedDate.map(isoFormatter.date))
XCTAssertEqual(media.fileType, mediaJson.fileType)
XCTAssertEqual(media.id, mediaJson.id)
XCTAssertEqual(media.isInFavorite, mediaJson.isInFavorite)
XCTAssertEqual(media.lastModifiedDate, mediaJson.lastModifiedDate.map(isoFormatter.date))
XCTAssertEqual(media.order, mediaJson.order)
XCTAssertEqual(media.type, mediaJson.type)
let mediaOwner = media.owner
let mediaOwnerJson = mediaJson.owner!
XCTAssertEqual(mediaOwner?.uuid, mediaOwnerJson.uuid)
XCTAssertEqual(mediaOwner?.firstName, mediaOwnerJson.firstName)
XCTAssertEqual(mediaOwner?.lastName, mediaOwnerJson.lastName)
} catch {
XCTFail(error.localizedDescription)
}
}
}
func testDisableProperties() {
performAndWaitOnViewContext { context in
var decoder = ManagedObjectJsonDecoder<Post>()
guard case .shared = decoder[\.owner?.firstName].decodeStrategy,
case .shared = decoder[\.owner].decodeStrategy else { return XCTFail() }
decoder[\.owner?.firstName].decodeStrategy = .disable
guard case .disable = decoder[\.owner?.firstName].decodeStrategy
else { return XCTFail() }
let json = Json.test[0]!
do {
let post = try decoder.decodeObject(json: json, context: context)
let owner = post.owner
XCTAssertNil(owner?.firstName)
XCTAssertEqual(owner?.lastName, json.owner?.lastName)
XCTAssertEqual(owner?.uuid, json.owner?.uuid)
XCTAssertNotNil(decoder[\.owner].decoder)
} catch {
XCTFail(error.localizedDescription)
}
(try? decoder.entityDecoder.findObject(json: json, context: context) as? Post)?.owner = nil
do {
decoder[\.owner].decodeStrategy = .disable
XCTAssertNil(decoder[\.owner].decoder)
let post = try decoder.decodeObject(json: json, context: context)
XCTAssertNil(post.owner)
} catch {
XCTFail(error.localizedDescription)
}
}
}
}
|
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var swipeView: UIView!
@IBAction func showArrayTable(sender: AnyObject) {
self.performSegueWithIdentifier("showArrayTable", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
initiateSwipeHorizontal()
initiateTap()
}
// ------------------------------------------------------
// ==================
// Swipe Horizontally
// ==================
func initiateSwipeHorizontal() {
let swipeHorizontal = UISwipeGestureRecognizer(target: self, action: "swipedHorizontal:")
swipeHorizontal.direction = UISwipeGestureRecognizerDirection.Left | UISwipeGestureRecognizerDirection.Right
self.swipeView.addGestureRecognizer(swipeHorizontal)
}
func swipedHorizontal(sender: UISwipeGestureRecognizer) {
var secondVC = self.storyboard?.instantiateViewControllerWithIdentifier("secondVC") as SecondViewController
self.presentViewController(secondVC, animated: true, completion: nil)
}
// ------------------------------------------------------
// ===
// Tap
// ===
func initiateTap() {
let tap = UITapGestureRecognizer(target: self, action: "tapped:")
tap.numberOfTapsRequired = 1
self.swipeView.addGestureRecognizer(tap)
}
func tapped(send: UITapGestureRecognizer) {
self.performSegueWithIdentifier("showArrayTable", sender: self)
}
// ------------------------------------------------------
/*
TODO one: Hook up a swipeable area on the home screen that must present a modal dialog when swiped. You must create the modal dialog and present it in CODE (not the storyboard).
TODO two: Add an imageview to the modal dialog presented in TODO two.
TODO three: Add and hook up a ‘dismiss’ button below the above mentioned image view that will dismiss the modal dialog. Do this in CODE.
TODO four: Hook up the button on the home screen to push ArrayTableViewController into view (via the navigation controller) when tapped. Do this by triggering a segue from this view controller. The method you are looking for is performSegueWithIdentifier. Find the identifier from the storyboard.
*/
}
|
//
// NewsNetworkManager.swift
// StyleOfMe
//
// Created by MattHew Phraxayavong on 1/8/21.
//
import Foundation
class NewsNetworkManager {
static let shared = NewsNetworkManager()
let imageCache = NSCache<NSString, NSData>()
private let baseURL = "https://newsapi.org/v2/"
private let USTopHeadline = "top-headlines?country=us"
func getNews(completion: @escaping([Articles]?) -> Void) {
let urlString = "\(baseURL)\(USTopHeadline)&apiKey=\(NetworkProperties.newsKey)"
guard let url = URL(string: urlString) else {
return
}
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard err == nil, let data = data else {
completion(nil)
return
}
let newsArticles = try? JSONDecoder().decode(ArticlesModel.self, from: data)
newsArticles == nil ? completion(nil) : completion(newsArticles?.articles)
}.resume()
}
func getImage(urlString: String, completion: @escaping (Data?) -> Void) {
guard let url = URL(string: urlString) else {
return
}
if let cachedImage = imageCache.object(forKey: NSString(string: urlString)) {
completion(cachedImage as Data)
} else {
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard err == nil, let data = data else {
completion(nil)
return
}
self.imageCache.setObject(data as NSData, forKey: NSString(string: urlString))
completion(data)
}.resume()
}
}
}
|
//
// BaseService.swift
// RiBoScheduleAssistant
//
// Created by Rin Pham on 3/14/18.
// Copyright © 2018 Rin Pham. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
typealias Completion = (_ data: JSON, _ statusCode: Int?, _ error: String?) -> Void
typealias Result = (_ data: Any, _ statusCode: Int?, _ error: String?) -> Void
typealias ListResult = (_ data: [Any], _ statusCode: Int?, _ error: String?) -> Void
typealias ObjectLink = (link: String, paramater: [String: Any])
class BaseService {
static func requestService(apiPath: String?, method: HTTPMethod, parameters: Parameters?, completion: @escaping Completion) {
if let apiPath = apiPath {
Alamofire.SessionManager.default.session.configuration.timeoutIntervalForRequest = 120
Alamofire.request(apiPath, method: method, parameters: parameters, headers: AppLinks.header).responseJSON { response in
switch response.result {
case .success(let value):
if let error = JSON(value)["detail"].string {
completion(JSON.null, response.response?.statusCode, error)
} else {
completion(JSON(value), response.response?.statusCode, nil)
}
case .failure(let error):
completion(JSON.null, response.response?.statusCode, error.localizedDescription)
}
}
}
}
}
|
//
// AppLaunch.swift
// Piicto
//
// Created by OkuderaYuki on 2018/01/06.
// Copyright © 2018年 SmartTech Ventures Inc. All rights reserved.
//
import Foundation
final class AppLaunch: NSObject {
/// アプリ初回起動済みの状態を保存する
static func completedFirstLaunch() {
UserDefaults().set(true, forKey: .completedFirstLaunch)
}
/// アプリ初回起動かどうか判定する
///
/// - Returns: true: 初回起動, false: 非初回起動
static func isFirstTime() -> Bool {
guard let completedFirstLaunch = UserDefaults().bool(forKey: .completedFirstLaunch) else {
return true
}
return !completedFirstLaunch
}
}
|
//
// ViewController.swift
// test
//
// Created by Michael Nienaber on 9/12/2015.
// Copyright © 2015 Michael Nienaber. All rights reserved.
//
import Foundation
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
@IBOutlet weak var imagePickerView: UIImageView!
@IBOutlet weak var cameraButton: UIBarButtonItem!
@IBOutlet weak var bottomToolBar: UIToolbar!
@IBOutlet weak var topNavBar: UINavigationBar!
@IBOutlet weak var shareOutlet: UIBarButtonItem!
@IBOutlet weak var saveMemeOutlet: UIBarButtonItem!
@IBOutlet weak var topFieldText: UITextField!
@IBOutlet weak var bottomFieldText: UITextField!
var meme: Meme!
var savedIndex: Int? = nil
let memeTextAttributes = [
NSStrokeColorAttributeName : UIColor.blackColor(),
NSForegroundColorAttributeName : UIColor.whiteColor(),
NSFontAttributeName : UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName : -2.0]
override func viewDidLoad() {
super.viewDidLoad()
topFieldText.defaultTextAttributes = memeTextAttributes
bottomFieldText.defaultTextAttributes = memeTextAttributes
topFieldText.text = "TOP TEXT"
bottomFieldText.text = "BOTTOM TEXT"
topFieldText.textAlignment = NSTextAlignment.Center
bottomFieldText.textAlignment = NSTextAlignment.Center
self.topFieldText.delegate = self
self.bottomFieldText.delegate = self
topFieldText.hidden = true
bottomFieldText.hidden = true
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
cameraButton.enabled = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
subscribeToKeyboardNotificationsExpand()
subscribeToKeyboardNotificationsCollapse()
shareOutlet.enabled = false
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
}
func imagePickerRefactor(sourceTypeVar: UIImagePickerControllerSourceType) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = sourceTypeVar
presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func pickAnImage(sender: AnyObject) {
imagePickerRefactor(UIImagePickerControllerSourceType.PhotoLibrary)
}
@IBAction func pickAnImageFromCamera(sender: AnyObject) {
imagePickerRefactor(UIImagePickerControllerSourceType.Camera)
}
func imagePickerController(picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.imagePickerView.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
topFieldText.hidden = false
bottomFieldText.hidden = false
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var newText: NSString = textField.text!
newText = newText.stringByReplacingCharactersInRange(range, withString: string)
return true
}
func textFieldDidBeginEditing(textField: UITextField) {
textField.text = ""
saveMemeOutlet.title = "Save"
shareOutlet.enabled = true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
func keyboardWillShow(notification: NSNotification) {
if bottomFieldText.isFirstResponder() {
bottomToolBar.hidden = true
view.frame.origin.y -= getKeyboardHeight(notification) - 44
}
}
func keyboardWillHide(notification: NSNotification) {
bottomToolBar.hidden = false
view.frame.origin.y = 0
}
func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.CGRectValue().height
}
func subscribeToKeyboardNotificationsExpand() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
saveMemeOutlet.enabled = true
}
func subscribeToKeyboardNotificationsCollapse() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
saveMemeOutlet.enabled = true
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
func unsubscribeFromKeyboardNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func startOver() {
dismissViewControllerAnimated(true, completion: nil)
}
func save(memedImage: UIImage) {
let meme = Meme(topString: topFieldText.text!, bottomString: bottomFieldText.text!, originalImage: imagePickerView.image!, memedImage: memedImage)
UIImageWriteToSavedPhotosAlbum(memedImage, nil, nil, nil)
let object = UIApplication.sharedApplication().delegate
let appDelegate = object as! AppDelegate
appDelegate.memes.append(meme)
}
func generateMemedImage() -> UIImage {
topNavBar.hidden = true
bottomToolBar.hidden = true
UIGraphicsBeginImageContext(self.view.frame.size)
self.view.drawViewHierarchyInRect(self.view.frame,
afterScreenUpdates: true)
let memedImage : UIImage =
UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
bottomToolBar.hidden = false
topNavBar.hidden = false
return memedImage
}
@IBAction func saveMemeButton(sender: AnyObject) {
switch saveMemeOutlet {
case saveMemeOutlet where saveMemeOutlet.title == "Save":
save(generateMemedImage())
startOver()
default:
startOver()
}
}
@IBAction func shareMeme(sender: UIBarButtonItem) {
let shareableMeme = [generateMemedImage()]
let activityView = UIActivityViewController(activityItems: shareableMeme, applicationActivities: nil)
presentViewController(activityView, animated: true, completion: nil)
save(generateMemedImage())
saveMemeOutlet.title = "Done"
}
}
|
//
// House.swift
// CatanProbGenerator
//
// Created by FredLohner on 5/Dec/15.
// Copyright (c) 2015 FredLohner. All rights reserved.
//
// Generated by PaintCode (www.paintcodeapp.com)
//
import UIKit
class CatanHouse: UIView {
override func drawRect(rect: CGRect) {
House.drawCanvas1()
}
}
public class House: NSObject {
//// Drawing Methods
public class func drawCanvas1() {
//// Rectangle Drawing
let rectanglePath = UIBezierPath(rect: CGRectMake(0, 8, 20, 10))
UIColor.blueColor().setFill()
rectanglePath.fill()
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(0, 8))
bezierPath.addLineToPoint(CGPointMake(20, 8))
bezierPath.addLineToPoint(CGPointMake(10.53, 1))
bezierPath.addLineToPoint(CGPointMake(0, 8))
bezierPath.closePath()
UIColor.blueColor().setFill()
bezierPath.fill()
}
}
|
//
// ViewController.swift
// Fira
//
// Created by 1181432 on 29/1/16.
// Copyright © 2016 FIB. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SwitchClickDelegate{
var selectedIndexPath:NSIndexPath!
var selectedManuals = [Int:NSIndexPath] ()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedIndexPath = indexPath
print("Hey, he seleccionat")
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
//let cell = tableView.dequeueReusableCellWithIdentifier("userAttribute", forIndexPath: indexPath)
if let cell = tableView.dequeueReusableCellWithIdentifier("manualCell", forIndexPath: indexPath) as? ProductTableViewCell {
cell.delegate = self
cell.path = indexPath
return cell
}
return UITableViewCell()
}
func onSwitchChange(active:Bool, indexPath: NSIndexPath) {
if(active) {print("He activat el switch de la linia " + String(indexPath.row) ) }
else {print("He DESACTIVAT el switch de la linia " + String(indexPath.row) ) }
}
}
|
//
// WinningDetailCell1.swift
// DaLeTou
//
// Created by 刘明 on 2017/3/7.
// Copyright © 2017年 刘明. All rights reserved.
//
import UIKit
class WinningDetailCell1: UITableViewCell {
static let heightOfCell: CGFloat = 60
let poolLabel = UILabel()
let poolMoneyLabel = UILabel()
let salesLabel = UILabel()
let salesMoneyLabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let screenWidth = Common.screenWidth
poolLabel.frame = CGRect(x: 0, y: 5, width: screenWidth*0.5, height: 25)
poolLabel.text = "奖池滚存"
poolLabel.textAlignment = NSTextAlignment.center
poolLabel.font = UIFont.systemFont(ofSize: 16)
self.contentView.addSubview(poolLabel)
poolMoneyLabel.frame = CGRect(x: 0, y: 30, width: screenWidth*0.5, height: 25)
poolMoneyLabel.textAlignment = NSTextAlignment.center
poolMoneyLabel.font = UIFont.systemFont(ofSize: 16)
self.contentView.addSubview(poolMoneyLabel)
salesLabel.frame = CGRect(x: screenWidth*0.5, y: 5, width: screenWidth*0.5, height: 25)
salesLabel.text = "全国销量"
salesLabel.textAlignment = NSTextAlignment.center
salesLabel.font = UIFont.systemFont(ofSize: 16)
self.contentView.addSubview(salesLabel)
salesMoneyLabel.frame = CGRect(x: screenWidth*0.5, y: 30, width: screenWidth*0.5, height: 25)
salesMoneyLabel.textAlignment = NSTextAlignment.center
salesMoneyLabel.font = UIFont.systemFont(ofSize: 16)
self.contentView.addSubview(salesMoneyLabel)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setTextContent(poolMoney: String, salesMoney: String) {
poolMoneyLabel.text = poolMoney + "元"
salesMoneyLabel.text = salesMoney + "元"
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// ContentView.swift
// Pocker_Reminder
//
// Created by rui cai on 2019/12/27.
// Copyright © 2019 Buct. All rights reserved.
//
import SwiftUI
import Alamofire
struct ContentView: View {
var body: some View {
VStack{
Button(action: {
Alamofire.request("https://httpbin.org/get")
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)") //具体如何解析json内容可看下方“响应处理”部分
}
}
}) {
Text(/*@START_MENU_TOKEN@*/"Button"/*@END_MENU_TOKEN@*/)
}
}
//Text("Hello, World!")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// Entry.swift
// JournalCK
//
// Created by Jon Corn on 2/4/20.
// Copyright © 2020 Jon Corn. All rights reserved.
//
import Foundation
import CloudKit
// MARK: - String helpers
struct EntryStrings {
static let recordTypeKey = "Entry"
fileprivate static let titleKey = "title"
fileprivate static let bodyTextKey = "bodyText"
fileprivate static let timestampKey = "timestamp"
}
// MARK: - Entry Model
class Entry {
var title: String
var bodyText: String
var timestamp: Date
var ckRecordID: CKRecord.ID
init(title: String, bodyText: String, timestamp: Date = Date(), ckRecordID: CKRecord.ID = CKRecord.ID(recordName: UUID().uuidString)) {
self.title = title
self.bodyText = bodyText
self.timestamp = timestamp
self.ckRecordID = ckRecordID
}
}
// MARK: - Fetch record
extension Entry {
// fetch record
convenience init?(ckRecord: CKRecord) {
guard let title = ckRecord[EntryStrings.titleKey] as? String,
let bodyText = ckRecord[EntryStrings.bodyTextKey] as? String,
let timestamp = ckRecord[EntryStrings.timestampKey] as? Date
else {return nil}
self.init(title: title, bodyText: bodyText, timestamp: timestamp, ckRecordID: ckRecord.recordID)
}
}
// MARK: - Create record
extension CKRecord {
convenience init(entry: Entry) {
self.init(recordType: EntryStrings.recordTypeKey)
self.setValuesForKeys([
EntryStrings.titleKey : entry.title,
EntryStrings.bodyTextKey : entry.bodyText,
EntryStrings.timestampKey : entry.timestamp
])
}
}
|
//
// TbRouter.swift
// luffy
//
// Created by 季勤强 on 2020/5/12.
// Copyright © 2020 dyljqq. All rights reserved.
//
import Foundation
enum TbRouter {
case itemInfo(_ itemId: Int)
}
extension TbRouter: URLRequestConvertible {
var baseURLString: String {
return "http://h5api.m.taobao.com"
}
var path: String {
switch self {
case .itemInfo:
return "/h5/mtop.taobao.detail.getdetail/6.0/"
}
}
var headers: [String: String] {
var headers = [
"Accept": "*/*",
"Accept-Language": "zh-CN",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) FxiOS/10.6b8836 Mobile/14G60 Safari/603.3.8",
]
switch self {
case .itemInfo(let itemId):
headers["Referer"] = "https://detail.m.tmall.com/item.htm?spm=a220m.6910245.0.0.55b17434eiwv4f&id=\(itemId)"
}
return headers
}
var params: Parameters {
switch self {
case .itemInfo(let itemId):
let timestamp = Date().timeIntervalSince1970
let dict = [
"itemNumId": "\(itemId)",
"itemId": "\(itemId)",
"exParams": "{\"id\": \"\(itemId)\"}",
"detail_v": "8.0.0",
"utdid": "1"
]
let data = try! JSONSerialization.data(withJSONObject: dict, options: [])
let str = String(data: data, encoding: .utf8)!
return [
"jsv": "2.5.7",
"appKey": 12574478,
"t": timestamp,
"sign": "7c9e1dedaa295fdb175d22c99746493b",
"api": "mtop.taobao.detail.getdetail",
"v": "6.0",
"ttid": "2018@taobao_h5_9.9.9",
"type": "json",
"dataType": "json",
"data": str
]
}
}
var method: HTTPMethod {
switch self {
case .itemInfo:
return .get
}
}
}
|
//
// Dawn.swift
// Pods
//
// Created by Meniny on 2017-08-01.
//
//
import Foundation
public struct Dawn {
public static var calendar: Calendar = Calendar.current
public var calendar: Calendar
public init(calendar c: Calendar) {
calendar = c
}
// MARK: - Leap Year
public static func checkLeapYear(_ year: Int) -> Bool {
return (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))
}
public func checkLeapYear(_ year: Int) -> Bool {
return Dawn.checkLeapYear(year)
}
// MARK: - Compare
// Class
public static func compare(date: Date, ifEarlier another: Date) -> Bool {
return date.isEarlier(than: another)
}
public static func compare(date: Date, ifEarlierThanOrEqualTo another: Date) -> Bool {
return date.isEarlierThanOrEqualTo(another)
}
public static func compare(date: Date, ifLater another: Date) -> Bool {
return date.isLater(than: another)
}
public static func compare(date: Date, ifLaterThanOrEqualTo another: Date) -> Bool {
return date.isLaterThanOrEqualTo(another)
}
public static func compare(date: Date, ifEqualTo another: Date) -> Bool {
return date.isEqualTo(another)
}
public static func compare(date: Date, ifNotEqualTo another: Date) -> Bool {
return !date.isEqualTo(another)
}
// Instance
public func compare(date: Date, ifEarlier another: Date) -> Bool {
return date.isEarlier(than: another)
}
public func compare(date: Date, ifEarlierThanOrEqualTo another: Date) -> Bool {
return date.isEarlierThanOrEqualTo(another)
}
public func compare(date: Date, ifLater another: Date) -> Bool {
return date.isLater(than: another)
}
public func compare(date: Date, ifLaterThanOrEqualTo another: Date) -> Bool {
return date.isLaterThanOrEqualTo(another)
}
public func compare(date: Date, ifEqualTo another: Date) -> Bool {
return date.isEqualTo(another)
}
public func compare(date: Date, ifNotEqualTo another: Date) -> Bool {
return !date.isEqualTo(another)
}
// MARK: - Calculating
public static func dateBy(_ calculating: TimeCalculatingOperation, _ value: Int, of type: TimePeriodSize, to date: Date) -> Date? {
return Dawn.calendar.date(by: calculating, value, of: type, to:date)
}
public func dateBy(_ calculating: TimeCalculatingOperation, _ value: Int, of type: TimePeriodSize, to date: Date) -> Date? {
return calendar.date(by: calculating, value, of: type, to:date)
}
// MARK: Adding components to dates
public static func dateByAdding(_ value: Int, of type: TimePeriodSize, to date: Date) -> Date? {
return Dawn.calendar.date(by: .adding, value, of: type, to: date)
}
public func dateByAdding(_ value: Int, of type: TimePeriodSize, to date: Date) -> Date? {
return Dawn.calendar.date(by: .adding, value, of: type, to: date)
}
public static func dateByAdding(years: Int, to date: Date) -> Date? {
return Dawn.calendar.date(byAdding: years, of: .year, to: date)
}
public static func dateByAdding(months: Int, to date: Date) -> Date? {
return Dawn.calendar.date(byAdding: months, of: .month, to: date)
}
public static func dateByAdding(weeks: Int, to date: Date) -> Date? {
return Dawn.calendar.date(byAdding: weeks, of: .week, to: date)
}
public static func dateByAdding(days: Int, to date: Date) -> Date? {
return Dawn.calendar.date(byAdding: days, of: .day, to: date)
}
public static func dateByAdding(hours: Int, to date: Date) -> Date? {
return Dawn.calendar.date(byAdding: hours, of: .hour, to: date)
}
public static func dateByAdding(minutes: Int, to date: Date) -> Date? {
return Dawn.calendar.date(byAdding: minutes, of: .minute, to: date)
}
public static func dateByAdding(seconds: Int, to date: Date) -> Date? {
return Dawn.calendar.date(byAdding: seconds, of: .second, to: date)
}
// MARK: Subtracting components from dates
public static func dateBySubtracting(_ value: Int, of type: TimePeriodSize, to date: Date) -> Date? {
return Dawn.calendar.date(by: .subtracting, value, of: type, to: date)
}
public func dateBySubtracting(_ value: Int, of type: TimePeriodSize, to date: Date) -> Date? {
return calendar.date(by: .subtracting, value, of: type, to: date)
}
public static func dateBySubtracting(years: Int, from date: Date) -> Date? {
return Dawn.calendar.date(bySubtracting: years, of: .year, to: date)
}
public static func dateBySubtracting(months: Int, from date: Date) -> Date? {
return Dawn.calendar.date(bySubtracting: months, of: .month, to: date)
}
public static func dateBySubtracting(weeks: Int, from date: Date) -> Date? {
return Dawn.calendar.date(bySubtracting: weeks, of: .week, to: date)
}
public static func dateBySubtracting(days: Int, from date: Date) -> Date? {
return Dawn.calendar.date(bySubtracting: days, of: .day, to: date)
}
public static func dateBySubtracting(hours: Int, from date: Date) -> Date? {
return Dawn.calendar.date(bySubtracting: hours, of: .hour, to: date)
}
public static func dateBySubtracting(minutes: Int, from date: Date) -> Date? {
return Dawn.calendar.date(bySubtracting: minutes, of: .minute, to: date)
}
public static func dateBySubtracting(seconds: Int, from date: Date) -> Date? {
return Dawn.calendar.date(bySubtracting: seconds, of: .second, to: date)
}
// MARK: - Counting components between dates
public static func counting(_ expected: DateCountingUnit, from firstDate: Date, to secondDate: Date) -> Int? {
return Dawn.calendar.counting(expected, from: firstDate, to: secondDate)
}
public static func years(from firstDate: Date, to secondDate: Date) -> Int? {
return Dawn.calendar.counting(.years, from: firstDate, to: secondDate)
}
public static func months(from firstDate: Date, to secondDate: Date) -> Int? {
return Dawn.calendar.counting(.months, from: firstDate, to: secondDate)
}
public static func weeks(from firstDate: Date, to secondDate: Date) -> Int? {
return Dawn.calendar.counting(.weeks, from: firstDate, to: secondDate)
}
public static func days(from firstDate: Date, to secondDate: Date) -> Int? {
return Dawn.calendar.counting(.days, from: firstDate, to: secondDate)
}
}
|
//
// ViewController.swift
// ActivityIndicator
//
// Created by AMANBOLAT BALABEKOV on 15.09.16.
// Copyright © 2016 AMANBOLAT BALABEKOV. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var indicatorView: AmanIndicator?
override func viewDidLoad() {
super.viewDidLoad()
indicatorView = AmanIndicator(vc: self, message: "Loading...")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showBtnPressed(_ sender: AnyObject) {
indicatorView?.show()
}
@IBAction func hideBtnPressed(_ sender: AnyObject) {
indicatorView?.hide()
}
}
|
//
// SignInView.swift
// Twitter
//
// Created by Mark on 19/12/2019.
// Copyright © 2019 Twitter. All rights reserved.
//
import UIKit
protocol SignInDelegate {
func signIn(emailAddress: String, password: String) -> Void
func register() -> Void
}
class SignInView: UIView {
var didTapSignIn: SignInDelegate?
var subViews: [UIView]!
let imageLogo: UIImageView = {
let image = UIImage(named: "twitter")
let imageLogo = UIImageView(image: image)
imageLogo.contentMode = .scaleAspectFill
imageLogo.translatesAutoresizingMaskIntoConstraints = false
return imageLogo
}()
let emailField: UITextField = {
let textField = UITextField()
textField.placeholder = "Email"
textField.translatesAutoresizingMaskIntoConstraints = false
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.backgroundColor = .white
return textField
}()
let passwordField: UITextField = {
let textField = UITextField()
textField.placeholder = "Password"
textField.translatesAutoresizingMaskIntoConstraints = false
textField.isSecureTextEntry = true
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.backgroundColor = .white
return textField
}()
let signInButton: UIButton = {
let button = UIButton()
button.setTitle("Signin", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor(named: "TwitterBlue")
button.layer.cornerRadius = 8
button.addTarget(self, action: #selector(login), for: .touchUpInside)
return button
}()
let registerButton: UIButton = {
let button = UIButton()
button.setTitle("Register", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor(named: "TwitterBlue")
button.layer.cornerRadius = 8
button.addTarget(self, action: #selector(registerSegue), for: .touchUpInside)
return button
}()
let copyrightInfo: UILabel = {
let copyrightInfo = UILabel()
copyrightInfo.text = "Twitter Inc © 2019"
copyrightInfo.translatesAutoresizingMaskIntoConstraints = false
return copyrightInfo
}()
let stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .fill
stackView.spacing = 8
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
//MARK: Initialiser
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: Setup View
fileprivate func setupView() {
backgroundColor = .systemBackground
addSubview(imageLogo)
addSubview(stackView)
addSubview(copyrightInfo)
self.subViews = [emailField, passwordField, signInButton, registerButton]
subViews.forEach { view in
addSubview(view)
stackView.addArrangedSubview(view)
}
setupConstraints()
}
//MARK: Constraints
fileprivate func setupConstraints() {
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20),
stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20),
stackView.centerYAnchor.constraint(equalTo: centerYAnchor),
signInButton.heightAnchor.constraint(equalToConstant: 45),
registerButton.heightAnchor.constraint(equalToConstant: 45),
imageLogo.centerXAnchor.constraint(equalTo: stackView.centerXAnchor),
imageLogo.bottomAnchor.constraint(equalTo: stackView.topAnchor, constant: -40),
imageLogo.widthAnchor.constraint(equalToConstant: 176),
imageLogo.heightAnchor.constraint(equalToConstant: 143),
copyrightInfo.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -30),
copyrightInfo.centerXAnchor.constraint(equalTo: centerXAnchor)
])
}
@objc fileprivate func registerSegue() {
register()
}
@objc fileprivate func login() {
signIn(emailAddress: emailField.text!, password: passwordField.text!)
}
}
extension SignInView: SignInDelegate {
func register() {
//Segue to register page
didTapSignIn?.register()
}
func signIn(emailAddress: String, password: String) {
didTapSignIn?.signIn(emailAddress: emailAddress, password: password)
}
}
|
//
// AddressTableViewCell.swift
// MarketPlace
//
// Created by Administrator on 25/08/16.
// Copyright © 2016 inpanr07. All rights reserved.
//
import UIKit
class AddressTableViewCell: UITableViewCell {
@IBOutlet weak var addTitleLabel: UILabel!
@IBOutlet weak var editaddressLabel: UITextView!
@IBOutlet weak var separatorLabel: UILabel!
@IBOutlet weak var editView: UIView!
@IBOutlet weak var addSetBtn: UIButton!
@IBOutlet weak var addEditBtn: UIButton!
@IBOutlet weak var addNameLabel: UILabel!
@IBOutlet weak var deleteBtn: UIButton!
@IBAction func editAddressButton(sender: AnyObject) {
// address
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
addEditBtn.layer.borderWidth = 1;
addEditBtn.layer.borderColor = UIColor(red: 51.0/255.0, green: 51.0/255.0, blue: 51.0/255.0, alpha: 1).CGColor
addSetBtn.layer.borderWidth = 1;
addSetBtn.layer.borderColor = UIColor(red: 31.0/255.0, green: 75.0/255.0, blue: 164.0/255.0, alpha: 1).CGColor
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// CountriesISO.swift
// Covid-19
//
// Created by yosef elbosaty on 5/27/20.
// Copyright © 2020 yosef elbosaty. All rights reserved.
//
import Foundation
import SwiftyJSON
struct CountriesISO{
var countryName: String
init?(dict: [String:JSON]){
guard let countryName = dict["name"]?.toString else{
return nil
}
self.countryName = countryName
}
}
|
//
// Game+Universe+Extension.swift
// Game of Life
//
// Created by Béla Szomathelyi on 2018. 11. 05..
// Copyright © 2018. Béla Szomathelyi. All rights reserved.
//
import UIKit
extension Game.Model.Universe {
typealias Dimensions = Game.Model.Dimensions
typealias Universe = Game.Model.Universe
init(dimensions: Dimensions, randomFill: Bool = true, _ editCloser: ((_ dimensions: Dimensions, _ cells: inout [[Bool]]) -> Void)? = nil){
var cells: [[Bool]]!
if (randomFill) {
cells = Universe.randomCells(withDimensions: dimensions)
} else {
cells = Universe.emptyCells(withDimensions: dimensions)
}
editCloser?(dimensions, &cells)
self.init(cells: cells, dimensions: dimensions)
}
private static func emptyCells(withDimensions dimensions: Dimensions) -> [[Bool]] {
var cells = [[Bool]]()
for _ in 0..<dimensions.height {
let row = Array(repeating: false, count: Int(dimensions.width))
cells.append(row)
}
return cells
}
private static func randomCells(withDimensions dimensions: Dimensions) -> [[Bool]] {
var cells = self.emptyCells(withDimensions: dimensions)
for i in 0..<dimensions.height {
for j in 0..<dimensions.width {
let value = arc4random_uniform(UInt32(2))
cells[Int(i)][Int(j)] = value == 0
}
}
return cells
}
}
|
/**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
extension Sequence where Iterator.Element == String {
var encoded: [String] {
return self.reduce([]) { acc, el in
guard let encodedTag = el.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else {
print(NSLocalizedString("Get Images By Tags Error: Failed to encode search tag", comment: ""))
return acc
}
return acc + [encodedTag.replacingOccurrences(of: "/", with: "%2F")]
}
}
}
|
//
// RouteCourierDetailCell.swift
// Vozon
//
// Created by Дастан Сабет on 31.05.2018.
// Copyright © 2018 Дастан Сабет. All rights reserved.
//
import UIKit
class RouteCourierDetailCell: UITableViewCell {
lazy var transportIcon: UIImageView = {
let icon = UIImageView()
icon.tintColor = UIColor(hex: "939393")
icon.contentMode = .scaleAspectFit
return icon
}()
lazy var transportName: UILabel = {
let label = UILabel()
label.textColor = UIColor.white.withAlphaComponent(0.9)
label.font = UIFont.systemFont(ofSize: 16)
return label
}()
lazy var transportExtra: UILabel = {
let label = UILabel()
label.textColor = UIColor(hex: "6B6B6B")
label.font = UIFont.systemFont(ofSize: 10, weight: .medium)
return label
}()
lazy var dateLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 10)
label.textColor = UIColor(hex: "6B6B6B")
return label
}()
lazy var fromShippingLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 10)
label.textColor = UIColor(hex: "6B6B6B")
label.text = Strings.fromShipping
return label
}()
lazy var startLocation: UILabel = {
let label = UILabel()
label.textColor = UIColor.white.withAlphaComponent(0.9)
label.font = UIFont.systemFont(ofSize: 16)
return label
}()
lazy var toShippingLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 10)
label.textColor = UIColor(hex: "6B6B6B")
label.text = Strings.toShipping
return label
}()
lazy var endLocation: UILabel = {
let label = UILabel()
label.textColor = UIColor.white.withAlphaComponent(0.9)
label.font = UIFont.systemFont(ofSize: 16)
return label
}()
lazy var separatorLine: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hex: "383838")
return view
}()
lazy var comment: UILabel = {
let label = UILabel()
label.textColor = UIColor.white.withAlphaComponent(0.9)
label.font = UIFont.systemFont(ofSize: 15)
label.numberOfLines = 0
return label
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
backgroundColor = UIColor(hex: "333333")
setupUI()
}
func setupUI() {
let stackVertical = UIStackView(arrangedSubviews: [transportName, transportExtra])
// stackVertical.distribution = .fill
stackVertical.spacing = 3
stackVertical.axis = .vertical
let stackHorizontal = UIStackView(arrangedSubviews: [transportIcon, stackVertical])
stackHorizontal.axis = .horizontal
stackHorizontal.distribution = .fill
stackHorizontal.spacing = 14
transportIcon.snp.makeConstraints { (make) in
make.width.equalTo(22)
}
addSubview(stackHorizontal)
stackHorizontal.snp.makeConstraints { (make) in
make.leading.equalTo(15)
make.top.equalTo(10)
make.trailing.equalTo(-15)
}
addSubview(dateLabel)
dateLabel.snp.makeConstraints { (make) in
make.trailing.equalTo(-15)
make.centerY.equalTo(transportName.snp.centerY)
}
addSubview(fromShippingLabel)
fromShippingLabel.snp.makeConstraints { (make) in
make.leading.equalTo(15)
make.top.equalTo(stackHorizontal.snp.bottom).offset(15)
make.trailing.equalTo(-15)
}
addSubview(endLocation)
endLocation.snp.makeConstraints { (make) in
make.leading.equalTo(15)
make.top.equalTo(fromShippingLabel.snp.bottom).offset(8)
make.trailing.equalTo(-15)
}
addSubview(toShippingLabel)
toShippingLabel.snp.makeConstraints { (make) in
make.leading.equalTo(15)
make.top.equalTo(endLocation.snp.bottom).offset(12)
make.trailing.equalTo(-15)
}
addSubview(startLocation)
startLocation.snp.makeConstraints { (make) in
make.leading.equalTo(15)
make.top.equalTo(toShippingLabel.snp.bottom).offset(8)
make.trailing.equalTo(-15)
}
addSubview(separatorLine)
separatorLine.snp.makeConstraints { (make) in
make.leading.equalTo(15)
make.trailing.equalTo(-15)
make.height.equalTo(1)
make.top.equalTo(startLocation.snp.bottom).offset(15)
}
addSubview(comment)
comment.snp.makeConstraints { (make) in
make.leading.equalTo(15)
make.trailing.equalTo(-15)
make.top.equalTo(separatorLine.snp.bottom).offset(15)
make.bottom.equalTo(-15)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
|
//
// MockTimer.swift
// AudioProcessorPackageDescription
//
// Created by Sam Meech-Ward on 2017-11-25.
//
@testable import AudioIO
import Foundation
import AudioIO
class MockTimer: TimerType {
var started = false
var stopped = false
var block: (() -> (Void))?
func tick() {
block?()
}
func start(_ block: @escaping () -> (Void)) {
self.block = block
started = true
}
func stop() {
stopped = true
}
}
|
//
// ContentView.swift
// Bookworm
//
// Created by /fam on 2/24/21.
//
import SwiftUI
import CoreData
struct PushButton: View{
let title:String
@Binding var isOn: Bool
var onColors = [Color.red,Color.yellow]
var offColors = [Color(white:0.6),Color(white:0.4)]
var body: some View {
Button(title){
self.isOn.toggle()
}.padding()
.background(LinearGradient(gradient: Gradient(colors: isOn ? onColors : offColors),startPoint:.top, endPoint:.bottom))
.foregroundColor(.white)
.clipShape(Capsule())
.shadow(radius:isOn ? 0 : 5)
}
}
struct ContentView: View {
@State var rememberMe=false
var body: some View {
VStack{
PushButton(title:"Remember Me",isOn:$rememberMe)
Text(rememberMe ? "On":"Off")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}
|
import Foundation
@testable import Element
@testable import Utils
class StatUtils{
/**
* Returns an index that can be used when toggeling time levels
*/
static func mouseLocIdx(_ mouseX:CGFloat, _ totalWidth:CGFloat, _ itemWidth:CGFloat) -> Int{
let rndTo:CGFloat = mouseX.roundTo(itemWidth)
Swift.print("rndTo: " + "\(rndTo)")
let idx:Int = (rndTo/itemWidth).int
return idx
}
/**
* Returns a progress value that can be used to stay in the same time period when toggeling between time-levels
*/
static func progress(_ timeBar:FastList, _ time:(prevTimeType:TimeType,curTimeType:TimeType), _ mouseLocIdx:Int, _ prevVisibleRange:Range<Int>)->CGFloat{/*0-1*/
let dp:TimeDP = timeBar.dataProvider as! TimeDP
let visibleRange:Range<Int> = prevVisibleRange//timeBar.visibleItemRange
let startIdx:Int = visibleRange.start
let idx:Int = startIdx + mouseLocIdx
Swift.print("offset idx: \(idx)")
//how do you set, just convert idx to progress
var dpProgress:CGFloat
switch time{
case (.year,.month):/*from year to month*/
Swift.print("⏳ from year to month")
let monthIdx:Int = YearDP.firstMonthInYear(idx)
Swift.print("monthIdx: " + "\(monthIdx)")
dpProgress = monthIdx.cgFloat/dp.count.cgFloat
Swift.print("dpProgress: " + "\(dpProgress)")
case (.month,.day):/*from month to day*/
Swift.print("⏳ from month to day")
Swift.print("Month offset idx: \(idx)")
Swift.print("visibleItemRange.start: " + "\(visibleRange.start)")
let dayIdx:Int = MonthDP.firstDayInMonth(idx,dp.yearRange)
dpProgress = dayIdx.cgFloat/dp.count.cgFloat
case (.month,.year):/*from month to year*/
Swift.print("⏳ from month to year")
let startYearIdx:Int = MonthDP.year(visibleRange.start, dp.yearRange)//sort of the offset
dpProgress = startYearIdx.cgFloat / dp.count.cgFloat
case (.day,.month):/*from day to month*/
Swift.print("⏳ from day to month")
let startMontIdx = DayDP.month(visibleRange.start, dp.yearRange)
dpProgress = startMontIdx.cgFloat / dp.count.cgFloat
default:
fatalError("This can't happen: \(time)" )
}
return dpProgress
}
}
|
//
// BaseCoordinator.swift
// Favorites Food
//
// Created by Pavel Kurilov on 19.11.2018.
// Copyright © 2018 Pavel Kurilov. All rights reserved.
//
import UIKit
protocol BaseCoordinatorDelegate: class {
func coordinatorRootViewControllerDidDeinit(coordinator: BaseCoordinator)
}
protocol BaseCoordinator: BaseCoordinatorDelegate {
var childCoordinators: [BaseCoordinator] { get set }
var baseDelegate: BaseCoordinatorDelegate? { get set }
var topController: UIViewController { get }
var topCoordinator: BaseCoordinator? { get }
func start()
}
extension BaseCoordinator {
var topCoordinator: BaseCoordinator? {
return childCoordinators.first
}
}
extension BaseCoordinator {
func remove(child coordinator: BaseCoordinator) {
if let index = childCoordinators.index(where: { $0 === coordinator }) {
childCoordinators.remove(at: index)
}
}
func dismissModalControllers(_ completion: (() -> Void)?) {
if let presentingViewController = topController.presentingViewController {
presentingViewController.dismiss(animated: true, completion: { [unowned self] in
self.dismissModalControllers(completion)
})
} else {
completion?()
}
}
func addChildCoordinator(_ coordinator: BaseCoordinator) {
childCoordinators.append(coordinator)
coordinator.baseDelegate = self
}
func coordinatorRootViewControllerDidDeinit(coordinator: BaseCoordinator) {
remove(child: coordinator)
}
}
|
//
// YoutubeVideoFetcher.swift
// J.YoutubeWatcher
//
// Created by JinYoung Lee on 21/02/2019.
// Copyright © 2019 JinYoung Lee. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
class YoutubeVideoFetcher: ContentFetcher {
private var searchKeyword: String = ""
private var onLoadRequest: DataRequest?
var SearchKeyWord:String = "" {
willSet {
searchKeyword = newValue
}
}
override func loadModel(loadDataListener: (([ContentData]) -> Void)?) {
guard !onLoading && !loadedAllDatas else {
return
}
onLoadRequest?.cancel()
onLoading = true
if searchKeyword.isEmpty {
onLoadRequest = YoutubeDAO().getPopularVideoSnippets(pageToken: nextPageToken, responseListener: { response in
self.nextPageToken = response["nextPageToken"] as? String
self.loadedAllDatas = !(self.nextPageToken != nil)
let pageInfo:[String:Any]? = response["pageInfo"] as? [String:Any]
self.totalCount = pageInfo?["totalResults"] as! Int
var newContentList = [ContentData]()
if let arrayOfData = response["items"] as? [Any] {
for dat in arrayOfData {
if let jsonData = dat as? [String:Any?] {
if let videoData = JsonParsor().parseVideoData(data: jsonData) {
self.addData(videoData)
newContentList.append(videoData)
}
}
}
loadDataListener?(newContentList)
self.onLoadFinish()
}
}) {
self.onLoadFail()
}
} else {
startSearch(loadDataListener)
}
}
private func startSearch(_ loadDataListener: (([ContentData]) -> Void)?) {
onLoadRequest = YoutubeDAO().getSearchVideoSnippets(keyword: searchKeyword, pageToken: nextPageToken, responseListener: { (response) in
self.nextPageToken = response["nextPageToken"] as? String
self.loadedAllDatas = !(self.nextPageToken != nil)
if let arrayOfData = response["items"] as? [Any] {
var newContentList = [ContentData]()
for dat in arrayOfData {
if let jsonData = dat as? [String:Any?] {
if let videoData = JsonParsor().parseSearchVideoData(data: jsonData) {
self.addData(videoData)
newContentList.append(videoData)
}
}
}
loadDataListener?(newContentList)
self.onLoadFinish()
}
}) {
self.onLoadFail()
}
}
func getDataCount() -> Int {
return savedData.count
}
}
|
import Foundation
extension FileManager {
// https://gist.github.com/brennanMKE/a0a2ee6aa5a2e2e66297c580c4df0d66
func directoryExistsAtPath(_ path: URL) -> Bool {
var isDirectory = ObjCBool(true)
let exists = self.fileExists(atPath: path.absoluteString, isDirectory: &isDirectory)
return exists && isDirectory.boolValue
}
func createDirectory(_ filePath: URL) -> URL? {
if !directoryExistsAtPath(filePath) {
do {
try self.createDirectory(atPath: filePath.path, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error.localizedDescription)
return nil
}
}
return filePath
}
func removeDirectory(_ filePath: URL) {
do {
try self.removeItem(atPath: filePath.path)
} catch {
print(error.localizedDescription)
}
}
func fileCountIn(_ filePath: URL) -> Int {
do {
let fileURLs = try self.contentsOfDirectory(at: filePath, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
return fileURLs.count
} catch {
print("Error while enumerating files \(filePath.path): \(error.localizedDescription)")
return -1
}
}
func getAllFilesIn(_ filePath: URL) -> [URL]? {
var fileURLs: [URL] = []
var sortedFileURLs: [URL] = []
do {
let keys = [URLResourceKey.contentModificationDateKey,
URLResourceKey.creationDateKey]
fileURLs = try self.contentsOfDirectory(at: filePath, includingPropertiesForKeys: keys, options: .skipsHiddenFiles)
} catch {
print("Error while enumerating files \(filePath.path): \(error.localizedDescription)")
return nil
}
let orderedFullPaths = fileURLs.sorted(by: { (url1: URL, url2: URL) -> Bool in
do {
let values1 = try url1.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
let values2 = try url2.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
if let date1 = values1.creationDate, let date2 = values2.creationDate {
return date1.compare(date2) == ComparisonResult.orderedDescending
}
} catch {
print("Error comparing : \(error.localizedDescription)")
return false
}
return true
})
for fileName in orderedFullPaths {
do {
let values = try fileName.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
if let date = values.creationDate{
sortedFileURLs.append(fileName)
}
}
catch {
print("Error sorting file URL's. : \(error.localizedDescription)")
return nil
}
}
return sortedFileURLs
}
func getMostRecentFileIn(_ filePath: URL) -> URL? {
return getAllFilesIn(filePath)?.first
}
}
|
//
// CitySearchView.swift
// weather
//
// Created by Kirill Titov on 13.11.2020.
//
import UIKit
class CitySearchView: UIView {
@IBOutlet weak var additionalInfo: UIButton!{
didSet {
additionalInfo.translatesAutoresizingMaskIntoConstraints = false
additionalInfo.backgroundColor = .white
}
}
@IBOutlet weak var cityName: UILabel!{
didSet {
cityName.translatesAutoresizingMaskIntoConstraints = false
cityName.backgroundColor = .white
}
}
@IBOutlet weak var cityTemperature: UILabel!{
didSet {
cityTemperature.translatesAutoresizingMaskIntoConstraints = false
cityTemperature.backgroundColor = .white
}
}
@IBOutlet weak var weatherIcon: UIImageView!{
didSet {
weatherIcon.translatesAutoresizingMaskIntoConstraints = false
weatherIcon.backgroundColor = .white
weatherIcon.bounds.size = CGSize(width: 100, height: 100)
weatherIcon.clipsToBounds = false
}
}
@IBOutlet weak var searchBar: UISearchBar! {
didSet {
searchBar.translatesAutoresizingMaskIntoConstraints = false
searchBar.backgroundColor = .white
searchBar.barTintColor = .white
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
|
//
// BookDetailTableViewCell.swift
// WindReadBook
//
// Created by 张旭 on 16/1/13.
// Copyright © 2016年 张旭. All rights reserved.
//
import UIKit
class BookDetailTableViewCell: UITableViewCell {
@IBOutlet weak var otherLabel: UILabel!
@IBOutlet weak var authorLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var imageCover: UIImageView!
var bookCoverImage:UIImage?{
didSet {
guard imageCover != nil else {return}
imageCover.image = bookCoverImage
}
}
var bookName:String?{
didSet {
guard nameLabel != nil else {return}
nameLabel.text = bookName
}
}
var bookAuthor:String?{
didSet {
guard authorLabel != nil else {return}
authorLabel.text = bookAuthor
}
}
var bookOther:String?{
didSet {
guard otherLabel != nil else {return}
otherLabel.text = bookOther
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// ImageCollectionViewCell.swift
// PizzaDemo
//
// Created by Pietro Gandolfi on 02/01/2019.
// Copyright © 2019 Pietro Gandolfi. All rights reserved.
//
import UIKit
class ImageCollectionViewCell: UICollectionViewCell {
static let identifier: String = "imageCell"
@IBOutlet weak var cellImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
}
|
//
// ViewController.swift
// demopapperscissorstone
//
// Created by Daniel on 2020/1/4.
// Copyright © 2020 Daniel. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var upImageView: UIImageView!
@IBOutlet weak var downImageView: UIImageView!
@IBOutlet weak var upLabel: UILabel!
let names = ["papper","scissor","stone"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
upLabel.text = "開始玩吧,你先選一個~"
}
@IBAction func scissorButton(_ sender: UIButton) {
downImageView.image = UIImage(named: "scissor")
upImageView.image = UIImage(named: "")
upLabel.text = ""
aiplay()
whowin()
}
@IBAction func stoneButton(_ sender: UIButton) {
downImageView.image = UIImage(named: "stone")
upImageView.image = UIImage(named: "")
upLabel.text = ""
aiplay()
whowin()
}
@IBAction func papperButton(_ sender: UIButton) {
downImageView.image = UIImage(named: "papper")
upImageView.image = UIImage(named: "")
upLabel.text = ""
aiplay()
whowin()
}
func aiplay(){
let randomname = names.randomElement()!
upImageView.image = UIImage(named: "\(randomname)")
}
func whowin(){
if upImageView.image == UIImage(named: "scissor"),downImageView.image == UIImage(named: "scissor"){
upLabel.text = "平手"
}else if upImageView.image == UIImage(named: "papper"),downImageView.image == UIImage(named: "papper"){
upLabel.text = "平手"
}else if upImageView.image == UIImage(named: "stone"),downImageView.image == UIImage(named: "stone"){
upLabel.text = "平手"
}else if upImageView.image == UIImage(named: "stone"),downImageView.image == UIImage(named: "papper"){
upLabel.text = "你贏了"
}else if upImageView.image == UIImage(named: "stone"),downImageView.image == UIImage(named: "scissor"){
upLabel.text = "電腦贏了"
}else if upImageView.image == UIImage(named: "papper"),downImageView.image == UIImage(named: "scissor"){
upLabel.text = "你贏了"
}else if upImageView.image == UIImage(named: "papper"),downImageView.image == UIImage(named: "stone"){
upLabel.text = "電腦贏了"
}else if upImageView.image == UIImage(named: "scissor"),downImageView.image == UIImage(named: "stone"){
upLabel.text = "你贏了"
}else if upImageView.image == UIImage(named: "scissor"),downImageView.image == UIImage(named: "papper"){
upLabel.text = "電腦贏了"
}
}
}
|
//
// ViewController.swift
// Project28
//
// Created by Anton Makeev on 24.04.2021.
//
import UIKit
import LocalAuthentication
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var secret: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
title = "Nothing to see here"
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(adjustKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(adjustKeyboard), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(saveSecretMessage), name: UIApplication.willResignActiveNotification, object: nil)
//navigationItem.setRightBarButton(nil, animated: true)
}
@IBAction func authenticateTapped(_ sender: UIButton) {
let context = LAContext()
var error: NSError?
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
let reason = "Identify yourself!"
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { [weak self] success, error in
DispatchQueue.main.async {
if success {
self?.unlockSecret()
if !KeychainWrapper.standard.hasValue(forKey: "Password") {
self?.askPasswordSet()
}
} else {
let ac = UIAlertController(title: "Authentication failed", message: "You could not be verified; please try again", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default){ [weak self] _ in
self?.askPassword()
})
self?.present(ac, animated: true)
}
}
}
} else {
let ac = UIAlertController(title: "Biometry unavailable", message: "Your device is not configured for biometrical authentication", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default) { [weak self] _ in
self?.askPassword()
})
present(ac, animated: true)
}
}
@objc func adjustKeyboard(notification: Notification) {
guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
let keyboardScreenEndFrame = keyboardValue.cgRectValue
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, to: view.window)
if notification.name == UIResponder.keyboardWillHideNotification {
secret.contentInset = .zero
} else {
secret.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height - view.safeAreaInsets.bottom, right: 0)
}
secret.scrollIndicatorInsets = secret.contentInset
let selectedRange = secret.selectedRange
secret.scrollRangeToVisible(selectedRange)
}
func unlockSecret() {
secret.isHidden = false
title = "Secret stuff!"
secret.text = KeychainWrapper.standard.string(forKey: "SecretMessage") ?? ""
let rightButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(saveSecretMessage))
navigationItem.setRightBarButton(rightButtonItem, animated: true)
}
@objc func saveSecretMessage() {
guard secret.isHidden == false else { return }
KeychainWrapper.standard.set(secret.text, forKey: "SecretMessage")
secret.resignFirstResponder()
secret.isHidden = true
title = "Nothing to see here"
navigationItem.setRightBarButton(nil, animated: true)
}
func askPasswordSet() {
guard secret.isHidden == false else { return }
let ac = UIAlertController(title: "Set password", message: "Password is needed in case biometry is unavaliable", preferredStyle: .alert)
ac.addTextField { textField in
textField.delegate = self
textField.isSecureTextEntry = true
textField.placeholder = "Enter password"
NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main) { _ in
if (ac.textFields![0].text!.count > 0) && (ac.textFields![0] == ac.textFields![1]) {
ac.actions[0].isEnabled = true
} else {
ac.actions[0].isEnabled = false
}
}
}
ac.addTextField { textField in
textField.delegate = self
textField.isSecureTextEntry = true
textField.placeholder = "Repeat password"
NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main) { _ in
if (ac.textFields![0].text!.count > 0) && (ac.textFields![0].text == ac.textFields![1].text) {
ac.actions[0].isEnabled = true
} else {
ac.actions[0].isEnabled = false
}
}
}
ac.addAction(UIAlertAction(title: "OK", style: .default) { _ in
if let password = ac.textFields?[0].text {
KeychainWrapper.standard.set(password, forKey: "Password")
}
})
ac.actions[0].isEnabled = false
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
present(ac, animated: true)
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let maxLength = 8
let currentString: NSString = (textField.text ?? "") as NSString
let newString: NSString =
currentString.replacingCharacters(in: range, with: string) as NSString
return newString.length <= maxLength
}
func askPassword() {
let ac = UIAlertController(title: "Enter password", message: nil, preferredStyle: .alert)
ac.addTextField { textField in
textField.isSecureTextEntry = true
}
ac.addAction(UIAlertAction(title: "OK", style: .default) { [weak self] _ in
guard let keychainPassword = KeychainWrapper.standard.string(forKey: "Password") else { return }
let password = ac.textFields![0].text ?? ""
if password == keychainPassword {
self?.unlockSecret()
} else {
let wrongAlert = UIAlertController(title: "Wrong Password", message: "Try again", preferredStyle: .alert)
wrongAlert.addAction(UIAlertAction(title: "OK", style: .default) { _ in self?.askPassword() })
self?.present(wrongAlert, animated: true)
}
}
)
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
present(ac, animated: true)
}
}
|
import Foundation
import TinyConstraints
typealias StateConstraints = [String: Constraints]
typealias StateColor = [String: UIColor]
enum State: String, CaseIterable {
case first
case second
case third
case fourth
func next() -> State? {
switch self {
case .first: return .second
case .second: return .third
case .third: return .fourth
case .fourth: return .first
}
}
func previous() -> State? {
switch self {
case .first: return .fourth
case .second: return .first
case .third: return .second
case .fourth: return .third
}
}
}
|
//
// Created by Jasmin Suljic on 02/09/2020.
// Copyright (c) 2020 CocoaPods. All rights reserved.
//
import Foundation
import Alamofire
import Monri
public class OrdersRepository {
public let authenticityToken: String
public init(authenticityToken: String) {
self.authenticityToken = authenticityToken
}
var apiOptions: MonriApiOptions {
MonriApiOptions(authenticityToken: authenticityToken, developmentMode: true)
}
public func createPayment(_ callback: @escaping (NewPaymentResponse?) -> Void) {
Alamofire.request("https://mobile.webteh.hr/example/create-payment-session",
method: .post,
// parameters: ["skip_authentication":"true"],
parameters: [:],
encoding: JSONEncoding.default)
.responseJSON { dataResponse in
guard let data = dataResponse.data else {
callback(nil)
return
}
do {
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
callback(nil)
return
}
print(json)
guard let response = NewPaymentResponse.fromJson(json) else {
callback(nil)
return
}
callback(response)
} catch {
callback(nil)
}
}
}
}
|
//
// TodoDetailViewController.swift
// J.Todo
//
// Created by JinYoung Lee on 24/07/2019.
// Copyright © 2019 JinYoung Lee. All rights reserved.
//
import Foundation
import UIKit
import RxCocoa
import RxSwift
class TodoDetailViewController: UIViewController {
private var dataModel: TodoDataModel?
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var registerDateLabel: UILabel!
@IBOutlet weak var contentTextView: UITextView!
private var modelDisposable: Disposable?
func setUpWithModel(_ model: TodoDataModel) {
dataModel = model
}
override func viewDidLoad() {
setUpNavigationBar()
setImageView()
modelDisposable = dataModel?.ModelData.subscribe({ (data) in
self.titleTextField.text = data.element?.title
self.contentTextView.text = data.element?.content
self.registerDateLabel.text = data.element?.getRegistedDate()
if let imageData = data.element?.imageData {
self.imageView.contentMode = .scaleAspectFill
self.imageView.image = UIImage(data: imageData)
}
})
}
override func viewDidDisappear(_ animated: Bool) {
modelDisposable?.dispose()
}
private func setUpNavigationBar() {
navigationItem.title = dataModel?.ModelData.value.title
let rightNavigationItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(updateData))
navigationItem.rightBarButtonItem = rightNavigationItem
titleTextField.resignFirstResponder()
contentTextView.resignFirstResponder()
titleTextField.isUserInteractionEnabled = false
contentTextView.isUserInteractionEnabled = false
imageView.isUserInteractionEnabled = false
}
private func setImageView() {
imageView.contentMode = .center
imageView.layer.cornerRadius = imageView.bounds.width/2
imageView.layer.masksToBounds = true
imageView.layer.borderWidth = 0.5
imageView.layer.borderColor = UIColor.lightGray.cgColor
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(updateImage)))
}
@objc private func updateData() {
let rightNavigationItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(finishUpdate))
navigationItem.rightBarButtonItem = rightNavigationItem
titleTextField.isUserInteractionEnabled = true
contentTextView.isUserInteractionEnabled = true
imageView.isUserInteractionEnabled = true
}
@objc private func finishUpdate() {
dataModel?.updateData(data: TodoDataModel.TodoData(title: titleTextField.text, content: contentTextView.text, registedDate: dataModel?.registedDate))
setUpNavigationBar()
Util.createToastMessage(title: "Update", message: "Update Success")
}
@objc private func updateImage() {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .savedPhotosAlbum
present(imagePicker, animated: true, completion: nil)
}
}
//MARK :- ImagePicker Delegate
extension TodoDetailViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true) {
if let cropView = Bundle.main.loadNibNamed("PhotoCropView", owner: self, options: nil)?.first as? PhotoCropView {
cropView.ProcessListener = self
cropView.setImageInfo(info)
UIApplication.shared.keyWindow?.addSubview(cropView)
}
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
//MARK :- CropImage Delegate Protocol
extension TodoDetailViewController: CroppingImageProtocol {
func onCompleteWithImage(_ image: UIImage) {
imageView.contentMode = .scaleAspectFill
imageView.image = image
dataModel?.ImageData = image.pngData()
}
func onFail() {
imageView.contentMode = .center
imageView.image = UIImage(named: "picture")
}
}
|
//
// WidgetSettingsSkeletonCell.swift
// WavesWallet-iOS
//
// Created by rprokofev on 06.08.2019.
// Copyright © 2019 Waves Platform. All rights reserved.
//
import UIKit
import Extensions
final class WidgetSettingsSkeletonCell: SkeletonTableCell, Reusable {
@IBOutlet weak var viewContainer: UIView!
override func awakeFromNib() {
super.awakeFromNib()
viewContainer.addTableCellShadowStyle()
}
}
|
// Mission Day 17 - Part 1 - Simple Sorting
func simpleSorting(_ arr: [Int]?) -> [Int]? {
if let array = arr {
return array.sorted()
}
return nil
}
let array = [14, 2, 1, 12]
if let arraySorted = simpleSorting(array) {
print(arraySorted)
}
|
//
// option.swift
// D2020
//
// Created by MacBook Pro on 3/16/20.
// Copyright © 2020 Abdallah Eslah. All rights reserved.
//
import Foundation
struct OptionFilter {
enum FilterType {
case nearest
case top_rate
}
var name: String
var type: FilterType
}
|
//
// PoiPopOverViewController.swift
// VacationPlanner
//
// Created by Cem Atilgan on 2019-03-23.
// Copyright © 2019 Cem Atilgan. All rights reserved.
//
import UIKit
import GooglePlaces
class PoiPopOverViewController: UIViewController {
@IBOutlet weak var topLevelStackView: UIStackView!
@IBOutlet weak var popOverNameLabel: UILabel!
@IBOutlet weak var popOverTypeLabel: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var poiDetails: POIObject?
private var gmsPlace: GMSPlace?
override func viewDidLoad() {
super.viewDidLoad()
setupView()
activityIndicator.startAnimating()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let fittedSize = topLevelStackView?.sizeThatFits(UIView.layoutFittingCompressedSize) {
preferredContentSize = CGSize(width: fittedSize.width + 30, height: fittedSize.height + 30)
}
}
@IBAction func addPlaceButtonTapped(_ sender: UIButton) {
performSegue(withIdentifier: Constants.Segues.showAddPlaceVC, sender: self)
}
func setupView(){
guard let poiDetails = poiDetails else { return }
popOverNameLabel.text = poiDetails.name
PlaceDetailsService.instance.getGooglePlaceDetails(for: poiDetails.id) { (success, place) in
guard success == true, let place = place, let placeType = place.types?.first else { return }
self.popOverTypeLabel.text = Utilities.editStringForPlaceTypes(text: placeType)
self.activityIndicator.stopAnimating()
self.activityIndicator.isHidden = true
self.gmsPlace = place
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationVC = segue.destination as? AddPlaceViewController{
destinationVC.place = gmsPlace
}
}
}
|
//
// ViewController.swift
// JokeApp
//
// Created by Patrick Aloueichek on 11/18/17.
// Copyright © 2017 Patrick Aloueichek. All rights reserved.
//
import UIKit
import CoreData
class MenuVC: UIViewController {
var jokeManagerSave : JokeManagerSave? = nil
var jokeManagerFetch : JokeManagerFetch? = nil
var networkManager : NetworkManager? = nil
var joke : Joke? = nil
var isJokeOfToday: Bool = false
@IBOutlet weak var textLabel: UILabel!
@IBAction func replayButton(_ sender: Any) {
self.updateTableContent()
}
@IBAction func shareButton(_ sender: Any) {
if let joke = joke {
let share = UIActivityViewController(activityItems: [joke.text], applicationActivities: nil)
self.present(share, animated: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.updateTableContent()
self.scheduleTimer()
}
func inject(jokeManagerSave : JokeManagerSave, jokeManagerFetch : JokeManagerFetch, networkManager : NetworkManager) {
self.jokeManagerSave = jokeManagerSave
self.jokeManagerFetch = jokeManagerFetch
self.networkManager = networkManager
}
private func scheduleTimer() {
let cal = Calendar(identifier: .gregorian)
let startOfToday = cal.startOfDay(for: Date())
if let startOfTomorrow = cal.date(byAdding: .day, value: 1, to: startOfToday) {
let interval = startOfTomorrow.timeIntervalSince(Date())
var timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { [weak self] timer in
self?.updateTableContent()
self?.scheduleTimer()
self?.isJokeOfToday = true
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func updateTableContent() {
do {
try self.jokeManagerFetch?.fetchedResultController.performFetch()
} catch let error {
print("Error: \(error.localizedDescription)") }
self.networkManager?.jokeGet{ (result) in
switch result {
case .Success(let data):
self.jokeManagerFetch?.clearData()
let joke = self.jokeManagerSave?.saveInCoreDataWith(saveJoke: data)
self.joke = joke
self.textLabel.text = data
case .Error(let message):
self.showAlertWith(title: "Error", message: message)
}
}
}
func showAlertWith(title: String, message: String, style: UIAlertControllerStyle = .alert) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: style)
let action = UIAlertAction(title: title, style: .default) { (action) in
self.dismiss(animated: true, completion: nil)
}
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
}
|
//
// EditProfileVC.swift
// Surface
//
// Created by Arvind Rawat on 02/04/18.
// Copyright © 2018 Appinventiv. All rights reserved.
//
import UIKit
import GooglePlaces
class EditProfileVC: UIViewController,UpdatePhoneNumber {
//MARK:- IBOUTLET
//===============
@IBOutlet weak var editProfileTableView: UITableView!
@IBOutlet weak var saveBtn: UIButton!
@IBOutlet weak var backBtn: UIButton!
//MARK:- PROPERTIES
//=================
var userInfo: UserInfoModel?
var proImage:UIImage?
var imageURL:String = ""
let editController = EditProfileController()
let verifyOTPController = VerifyOtpVC()
//MARK:- VIEWDIDLOAD
//==================
override func viewDidLoad() {
super.viewDidLoad()
setupNibs()
initialSetup()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
verifyOTPController.updatePhoneNumberDelegate = self
}
//MARK:- FUNCTIONS
//================
func initialSetup() {
if let userData = userInfo{
editController.userInfo = userData
}
editController.configureInputDict()
editProfileTableView.reloadData()
}
func setupNibs() {
editProfileTableView.delegate = self
editProfileTableView.dataSource = self
editProfileTableView.sectionHeaderHeight = 0.0;
editProfileTableView.sectionFooterHeight = 0.0;
let headerCell = UINib(nibName: "EditProfileHeader", bundle: nil)
self.editProfileTableView.register(headerCell, forHeaderFooterViewReuseIdentifier: "EditProfileHeader")
let headerInfo = UINib(nibName: "Textheader", bundle: nil)
self.editProfileTableView.register(headerInfo, forHeaderFooterViewReuseIdentifier: "Textheader")
let editInfoNib = UINib(nibName: "EditInfoCell", bundle: nil)
editProfileTableView.register(editInfoNib, forCellReuseIdentifier: "EditInfoCell")
let textFieldCell = UINib(nibName: "EditProfileTextFieldCell", bundle: nil)
editProfileTableView.register(textFieldCell, forCellReuseIdentifier: "EditProfileTextFieldCell")
let genderNib = UINib(nibName: "GenderCell", bundle: nil)
editProfileTableView.register(genderNib, forCellReuseIdentifier: "GenderCell")
editProfileTableView.estimatedRowHeight = 120
editProfileTableView.rowHeight = UITableViewAutomaticDimension
}
func configureAddressSelection() {
let autocompleteController = GMSAutocompleteViewController()
autocompleteController.delegate = self
let searchBarTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue : UIColor.white] as [String : Any]
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = searchBarTextAttributes
present(autocompleteController, animated: true, completion: nil)
}
func updateNumber(phone: String) {
editController.userInfo.mobile = phone
editProfileTableView.reloadSections([4], with: .none)
}
//MARK:- @objc Functions
//======================
@objc func maleBtnTapped(_ sender:UIButton) {
guard let cell = sender.tableViewCell() as? GenderCell else {
fatalError("GenderCell not initialised")
}
switch sender {
case cell.maleBtn:
cell.maleBtn.setTitleColor(UIColor.black, for: .selected)
cell.maleBtn.isSelected = true
cell.femaleBtn.isSelected = false
editController.userInfo.gender = "1"
default:
cell.femaleBtn.setTitleColor(UIColor.black, for: .selected)
cell.femaleBtn.isSelected = true
cell.maleBtn.isSelected = false
editController.userInfo.gender = "2"
}
// self.editProfileTableView.reloadRows(at: [[0,3]], with: .none)
}
@objc func editingChanged(_ textField:UITextField) {
guard let index = textField.tableViewIndexPath(tableView: self.editProfileTableView) else { return }
guard let text = textField.text else { return }
switch index.section {
case 0:
return
case 1:
switch index.row{
case 0:
editController.userInfo.user_name = text
case 1:
editController.userInfo.user_name = text
case 2:
editController.userInfo.bio = text
default:
return
}
editController.userInfoDict[index.section][index.row] = text
case 2:
editController.userInfo.location = text
editController.userInfoDict[index.section][index.row] = text
case 4:
if index.row == 0{
editController.userInfo.email = text
}else{
editController.userInfo.mobile = text
}
editController.userInfoDict[index.section][index.row] = text
default:
()
}
}
//MARK:- IBACTIONS
//================
@IBAction func saveBtnAction(_ sender: UIButton) {
editProfileTapped()
}
@IBAction func backBtnAction(_ sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}
}
//EXTENSION:- EditProfileVC
//==========================
extension EditProfileVC: UITableViewDelegate,UITableViewDataSource,ImagePickerDelegate{
func numberOfSections(in tableView: UITableView) -> Int {
return editController.inputDataDict.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return editController.inputDataDict[section].count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case 1:
if indexPath.row == 5{
return 110
}else{
return 60
}
default:
return 60
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let editTextFieldCell = tableView.dequeueReusableCell(withIdentifier: "EditProfileTextFieldCell") as? EditProfileTextFieldCell else{
fatalError("ProfileInfoCell not found")
}
let placeHolder = editController.inputDataDict[indexPath.section]
let infoData = editController.userInfoDict[indexPath.section]
switch indexPath.section{
case 0:
return UITableViewCell()
case 1:
if indexPath.row == 5{
guard let genderCell = tableView.dequeueReusableCell(withIdentifier: "GenderCell") as? GenderCell else{
fatalError("GenderCell not found")
}
genderCell.genderLabel.text = "GENDER"
genderCell.maleBtn.addTarget(self, action: #selector(maleBtnTapped(_:)), for: .touchUpInside)
genderCell.femaleBtn.addTarget(self, action: #selector(maleBtnTapped(_:)), for: .touchUpInside)
return genderCell
}else{
editTextFieldCell.infoTextField.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
editTextFieldCell.infoTextField.delegate = self
editTextFieldCell.populateData(index: indexPath, data: infoData[indexPath.row], placeHolder: placeHolder[indexPath.row])
return editTextFieldCell
}
case 2,3,4:
editTextFieldCell.infoTextField.delegate = self
editTextFieldCell.infoTextField.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
editTextFieldCell.populateData(index: indexPath, data: infoData[indexPath.row], placeHolder: placeHolder[indexPath.row])
return editTextFieldCell
default:
fatalError()
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let headerInfo = tableView.dequeueReusableHeaderFooterView(withIdentifier: "Textheader") as? Textheader else{
fatalError("ProfileHeader not found:")
}
switch section {
case 0:
guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "EditProfileHeader") as? EditProfileHeader else{
fatalError("ProfileHeader not found:")
}
header.delegate = self
if let profileImage = userInfo?.profile_image,!profileImage.isEmpty{
if let url = URL(string: profileImage) {
header.headerImage.kf.setImage(with: url, placeholder: nil)
}
}else{
header.headerImage.image = #imageLiteral(resourceName: "icTabBarProfileInactive")
}
return header
case 1:
headerInfo.headerInfoLabel.text = "Basic details"
return headerInfo
case 2:
headerInfo.headerInfoLabel.text = "Location"
return headerInfo
case 3:
headerInfo.headerInfoLabel.text = "Links"
return headerInfo
case 4:
headerInfo.headerInfoLabel.text = "Contact Information"
return headerInfo
default:
fatalError()
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0{
return 300
}else{
return 50
}
}
}
//MARK: extension GMSAutocompleteViewControllerDelegate methods
//============================================================
extension EditProfileVC: GMSAutocompleteViewControllerDelegate {
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
let index = IndexPath(row: 0, section: 1)
if let formattedAdd = place.formattedAddress {
editController.userInfo.location = formattedAdd
// signupController.userInfo.user_lat = String(place.coordinate.latitude)
// signupController.userInfo.user_long = String(place.coordinate.longitude)
editController.userInfoDict[2][0] = formattedAdd
}
self.editProfileTableView.reloadSections([2], with: .none)
self.view.endEditing(true)
dismiss(animated: true, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
print("Error: ", error.localizedDescription)
}
// User canceled the operation.
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
// configureSubmitButton()
dismiss(animated: true, completion: nil)
}
}
//EXTENSION:- CameraPicker
//===========================
extension EditProfileVC : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let imagePicked = info[UIImagePickerControllerOriginalImage] as? UIImage{
self.proImage = imagePicked
// let indexPath = IndexPath(row: 0, section: 0)
editController.profileImage = imagePicked
editProfileTableView.reloadSections([0], with: .fade)
}
if #available(iOS 11.0, *) {
if let imageUrl = info[UIImagePickerControllerImageURL] as? URL{
self.imageURL = String(describing: imageUrl)
uploadToS3()
}
} else {
// Fallback on earlier versions
}
picker.dismiss(animated: true, completion: nil)
}
func pickImage() {
let imagePicker = SingleImagePickerController()
imagePicker.delegate = self
imagePicker.target = self
imagePicker.startProcessing()
}
func check_usernameAndPhoneNum(_ params :JSONDictionary , indexpath : IndexPath){
WebServices.check_username(params: params, success: { [weak self] (result) in
guard let result = result else {return }
self?.error_Messages_forUniqueCheck(indexpath: indexpath, isExists: result["status"].boolValue)
}) {(error, code) in
Global.showToast(msg: error)
}
}
func error_Messages_forUniqueCheck(indexpath:IndexPath , isExists:Bool){
if let cell = self.editProfileTableView.cellForRow(at: indexpath) as? EditProfileTextFieldCell {
if isExists{
cell.infoTextField.addRightIcon(nil , imageSize: CGSize.zero)
}
else{
cell.infoTextField.addRightIcon(#imageLiteral(resourceName: "icUsernameTick"), imageSize: CGSize(width: 30, height: 30))
}
}
editProfileTableView.beginUpdates()
editProfileTableView.endUpdates()
}
}
//EXTENSION:- UITEXTFIELDELEGATES
//===============================
extension EditProfileVC: UITextFieldDelegate{
func textFieldDidEndEditing(_ textField: UITextField) {
guard let index = textField.tableViewIndexPath(tableView: self.editProfileTableView) else {return }
switch index.section {
case 1:
if index.row == 1{
if let text = textField.text,!text.isEmpty{
check_usernameAndPhoneNum(["username":text], indexpath: index)
}
}
default:
return
}
textField.layoutIfNeeded()
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
guard let indexPath = textField.tableViewIndexPath(tableView: editProfileTableView) else{
fatalError("error")
}
switch indexPath.section {
case 2:
configureAddressSelection()
return false
case 4:
if indexPath.row == 0{
let changeEmailVC = ChangeEmailVC.instantiate(fromAppStoryboard: .Profile)
self.navigationController?.pushViewController(changeEmailVC, animated: true)
}else{
let phoneNumberVC = ChangePhoneNumberVC.instantiate(fromAppStoryboard: .Profile)
self.navigationController?.pushViewController(phoneNumberVC, animated: true)
}
return false
default:
return true
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.containsEmoji{
return false
}
return true
}
}
//MARK:- API
extension EditProfileVC{
func uploadToS3() {
self.proImage?.uploadImageToS3(imageurl: "", uploadFolderName: "", compressionRatio: 0.5, success: { (boolValue, urlString) in
self.editController.userInfo.profile_image = urlString
self.editProfileTableView.reloadSections([0], with: .none)
}, progress: { (value) in
print(value)
}, failure: { (error) in
Global.showToast(msg:error.localizedDescription )
})
}
func editProfileTapped(){
let param = userInfo?.convertToDictionary(true)
WebServices.update_UserProfile(params: param!, success: { [weak self] (result) in
guard result != nil else {return }
}) {(error, code) in
Global.showToast(msg: error)
}
}
}
|
//
// Theme.swift
// cs193p2017Assignment
//
// Created by klioop on 2021/07/16.
//
import Foundation
enum Theme: String {
case face
case halloween
case construction
}
struct EmojiCollection {
static var faceEmojis = ["🤐", "😵💫", "🤢", "🤮", "🤧", "😷", "👺", "🤑"]
static var hallowinEmojis = ["👻", "👺", "👽", "💀", "☠️", "👹", "🎃"]
static var constructionEmojis = ["👷🏻♀️", "🧱", "🪓", "🔧", "🔨", "🔩", "⛏", "🚜", "🛠"]
static func returnEmojiSet(for theme: Theme) -> [String] {
switch theme {
case .face:
return EmojiCollection.faceEmojis
case .halloween:
return EmojiCollection.hallowinEmojis
case .construction:
return EmojiCollection.constructionEmojis
}
}
static func returnRandomEmojiSet() -> [String]{
let themes = [Theme.face, Theme.halloween, Theme.construction]
let themeChosen = themes.randomElement() ?? Theme.face
return returnEmojiSet(for: themeChosen)
}
}
|
//
// WinguSingleDotPageControl.swift
// winguSDK
//
// Created by Jakub Mazur on 31/03/2017.
// Copyright © 2017 wingu AG. All rights reserved.
//
import UIKit
class WinguSingleDotPageControl: NibLoadingView {
@IBOutlet weak var dotHeight: NSLayoutConstraint!
@IBOutlet weak var fillerHeight: NSLayoutConstraint!
@IBOutlet weak var baseView: UIView!
@IBOutlet weak var upperDot: UIView!
@IBOutlet weak var filler: UIView!
@IBOutlet weak var lowerDot: UIView!
var singleColor : UIColor? {
didSet {
self.upperDot.backgroundColor = singleColor
self.lowerDot.backgroundColor = singleColor
self.filler.backgroundColor = singleColor
}
}
var preloadedSelection : Bool = false
override func layoutSubviews() {
super.layoutSubviews()
self.update(self.preloadedSelection == true ? 1 : 0)
}
func update(_ value : CGFloat) {
self.fillerHeight.constant = self.frame.size.height/2*value
self.dotHeight.constant = (self.frame.size.height/2) + (self.frame.size.height/2*value)
self.upperDot.layer.cornerRadius = self.frame.size.width/2
self.lowerDot.layer.cornerRadius = self.frame.size.width/2
}
}
|
//
// TodayViewCell.swift
// todayWidget
//
// Created by Drew Lanning on 10/25/17.
// Copyright © 2017 Drew Lanning. All rights reserved.
//
import UIKit
import CoreData
class TodayViewCell: UITableViewCell {
@IBOutlet weak var activityTitle: UILabel!
@IBOutlet weak var newIncidentBtn: IncrementButton!
@IBOutlet weak var todayTotalLbl: UILabel!
@IBOutlet weak var mostRecentLbl: UILabel!
var addNewInstance: (() -> ())?
let generator = UINotificationFeedbackGenerator()
var context: NSManagedObjectContext?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setIncrementCounter(to count: Int) {
self.todayTotalLbl.text = "(\(count))"
}
func setMostRecent(to dateString: String?) {
mostRecentLbl.text = dateString != nil ? "- " + dateString! : ""
}
func configureCell(with activity: Activity, inContext context: NSManagedObjectContext) {
self.context = context
activityTitle.text = activity.name
setIncrementCounter(to: activity.getInstanceCount(forDate: Date()))
setMostRecent(to: activity.lastInstance?.getColloquialDateAndTime())
addNewInstance = { [weak self] in
activity.addNewInstance(withContext: self!.context!)
self?.setIncrementCounter(to: activity.getInstanceCount(forDate: Date()))
self?.setMostRecent(to: activity.lastInstance?.getColloquialDateAndTime())
}
self.selectionStyle = .none
}
func flashCell() {
UIView.animate(withDuration: 0, animations: {
self.contentView.backgroundColor = .white
}) { (complete) in
UIView.animate(withDuration: 1.0, animations: {
self.contentView.backgroundColor = .clear
})
}
}
@IBAction func activityHappened(sender: IncrementButton) {
UIView.animate(withDuration: 0.0, delay: 0, options: .transitionCrossDissolve, animations: {
self.generator.notificationOccurred(.success)
}, completion: { finished in
if let addNew = self.addNewInstance {
addNew()
self.flashCell()
do {
try self.context?.save()
Settings().didChangeObjectOn()
} catch {
print("could not save to context in today widget")
}
}
})
}
}
|
//
// ToolbarView.swift
// CatalystSampler
//
// Created by Kazuya Ueoka on 2020/01/18.
// Copyright © 2020 fromKK. All rights reserved.
//
import SwiftUI
import UIKit
struct ToolbarView: View {
var body: some View {
VStack {
Text("toolbar")
}
}
}
struct ToolbarView_Preview: PreviewProvider {
static var previews: some View {
ToolbarView()
}
}
|
import UIKit
import Quick
import Nimble
import Blindside
import CBGPromise
import SwiftyJSON
@testable import reddit_news_swift
class JSONClientSpec: QuickSpec {
override func spec() {
describe("JSONClientSpec") {
var urlSessionClient: URLSessionClientMock!
var subject: JSONClient!
beforeEach {
let injector = InjectorProvider.injector()
urlSessionClient = URLSessionClientMock()
injector.bind(URLSessionClient.self, toInstance: urlSessionClient)
subject = injector.getInstance(JSONClient.self) as! JSONClient
}
describe("-sendRequest") {
var future: Future<JSONResponse>!
beforeEach {
let url = URL(string: "https://www.google.com")!
let urlRequest = URLRequest(url: url)
future = subject.sendRequest(urlRequest: urlRequest)
}
it("should fetch the articles") {
expect(urlSessionClient.didCallSendRequest).to(equal(true));
expect(urlSessionClient.incomingURL?.url?.absoluteString).to(equal("https://www.google.com"))
}
describe("successfully fetching the articles") {
var data: Data!
let responseDictionary = [ "foo": "bar" ]
beforeEach() {
do {
data = try JSONSerialization.data(withJSONObject: responseDictionary)
} catch {
}
urlSessionClient.promise.resolve(.Success(data))
}
it("should deserialize the data into JSON") {
expect(future.value) == .Success(JSON(data: data))
}
}
describe("failing to fetch the articles") {
var data: Data!
let error = NetworkError(localizedTitle: "this is an error", localizedDescription: "this is description", code: 500)
beforeEach() {
urlSessionClient.promise.resolve(.Error(error))
}
it("should deserialize the data into JSON") {
expect(future.value) == .Error(error)
}
}
}
}
}
} |
//
// Created by Daniel Heredia on 2/27/18.
// Copyright © 2018 Daniel Heredia. All rights reserved.
//
// Intersection
// Solution using the slop-intercept equation form instead of the standard form
import Foundation
enum IntersectionType {
case noIntersection
case sameLine
case point
}
struct Point {
let x: Double
let y: Double
}
struct Line {
let m: Double
let b: Double
let isVertical: Bool
init(point1: Point, point2: Point) {
precondition(point1.x != point2.x || point1.y != point2.y)
self.isVertical = (point2.x - point1.x) == 0.0
if self.isVertical {
self.m = Double.infinity
self.b = point1.x
} else {
self.m = (point2.y - point1.y) / (point2.x - point1.x)
self.b = point2.y - self.m * point2.x
}
}
func isOnLine(point: Point) -> Bool {
if self.isVertical {
return point.x == self.b
} else {
return point.y == (self.m * point.x + self.b)
}
}
}
struct Segment {
let point1: Point
let point2: Point
let line: Line
init(point1: Point, point2: Point) {
self.point1 = point1
self.point2 = point2
self.line = Line(point1: point1, point2: point2)
}
func isOnSegment(point: Point) -> Bool{
if self.line.isOnLine(point: point) {
let minX = min(self.point1.x, self.point2.x)
let maxX = max(self.point1.x, self.point2.x)
let minY = min(self.point1.y, self.point2.y)
let maxY = max(self.point1.y, self.point2.y)
return minX <= point.x && maxX >= point.x &&
minY <= point.y && maxY >= point.y
} else {
return false
}
}
func getIntersection(segment: Segment) -> Point? {
if self.line.m == segment.line.m {
if self.line.b == segment.line.b {
if self.isOnSegment(point: segment.point1) {
return segment.point1
} else if self.isOnSegment(point: segment.point2) {
return segment.point2
}
}
return nil
}
var x = 0.0
if self.line.isVertical {
x = self.line.b
} else if segment.line.isVertical {
x = segment.line.b
} else {
x = (segment.line.b - self.line.b) / (self.line.m - segment.line.m)
}
let testSegment = self.line.isVertical ? segment : self
let y = testSegment.line.m * x + testSegment.line.b
let intersection = Point(x: x, y: y)
return self.isOnSegment(point: intersection) && segment.isOnSegment(point: intersection) ? intersection : nil
}
}
let s1Point1 = Point(x: 5.0, y: 5.0)
let s1Point2 = Point(x: 10.0, y: 10.0)
let s2Point1 = Point(x: -10.0, y: 10.0)
let s2Point2 = Point(x: 10.0, y: -10.0)
let segment1 = Segment(point1: s1Point1, point2: s1Point2)
let segment2 = Segment(point1: s2Point1, point2: s2Point2)
if let intersection = segment1.getIntersection(segment: segment2) {
print("Intersection: (x: \(intersection.x), y: \(intersection.y))")
} else {
print("No intersection")
}
|
//
// CGRequestCallbackModel.swift
// TestCG_CGKit
//
// Created by DY on 2017/5/25.
// Copyright © 2017年 apple. All rights reserved.
//
import UIKit
/// 数据请求回调对象
struct CGRequestCallbackModel {
let identifier : String?
let task : URLSessionTask
let successBlock : CGRequestSuccessBlock?
let failureBlock : CGRequestFailureBlock?
let completionBlock : CGRequestCompletion?
}
|
//
// HikesBadge.swift
// Landmarks
//
// Created by Matt Burke on 1/16/21.
//
import SwiftUI
struct HikesBadge: View {
var name: String
var body: some View {
VStack {
Badge()
.frame(width: 300.0, height: 300.0)
.scaleEffect(1.0 / 3.0)
.frame(width: 100, height: 100)
Text(name)
.font(.caption)
.accessibilityLabel("Badge for \(name)")
}
}
}
struct HikesBadge_Previews: PreviewProvider {
static var previews: some View {
HikesBadge(name: "Preview Testing")
}
}
|
import UIKit
extension UIView {
func rotate360Degrees(_ duration: CFTimeInterval = 1.0, completionDelegate: CAAnimationDelegate? = nil) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(M_PI * 2.0)
rotateAnimation.duration = duration
if let delegate: CAAnimationDelegate = completionDelegate {
rotateAnimation.delegate = delegate
}
self.layer.add(rotateAnimation, forKey: nil)
}
func fadeIn(_ duration: TimeInterval = 1.0, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in}) {
UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.alpha = 1.0
}, completion: completion) }
func fadeOut(_ duration: TimeInterval = 1.0, delay: TimeInterval = 0.0, completion: @escaping (Bool) -> Void = {(finished: Bool) -> Void in}) {
UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.alpha = 0.0
}, completion: completion)
}
}
|
//
// UserAction+CoreDataProperties.swift
// react-swift-test
//
// Created by ShichoChin on 2018/09/30.
// Copyright © 2018 Chin ShiCho. All rights reserved.
//
//
import Foundation
import CoreData
extension UserAction {
@nonobjc public class func fetchRequest() -> NSFetchRequest<UserAction> {
return NSFetchRequest<UserAction>(entityName: "UserAction")
}
@NSManaged public var todo: String?
@NSManaged public var date: NSDate?
@NSManaged public var update: NSDate?
@NSManaged public var title: String?
}
|
//
// ImageCollectionViewCell.swift
// ImageWithDescriptionUploader
//
// Created by Jora on 11/9/18.
// Copyright © 2018 Jora. All rights reserved.
//
import UIKit
class ImageCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var numberLabel: UILabel!
override func prepareForReuse() {
super.prepareForReuse()
backgroundColor = nil
numberLabel.textColor = .lightGray
}
override var isSelected: Bool {
didSet {
backgroundColor = isSelected ? .lightGray : nil
numberLabel.textColor = isSelected ? .white : .lightGray
}
}
}
|
//
// LoginController.swift
// Instagram-Clone-iOS
//
// Created by Arthur Octavio Jatobá Macedo Leite - ALE on 08/04/21.
//
import UIKit
import Firebase
class LoginController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var dontHaveAccountButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.isNavigationBarHidden = true
setupView()
}
func setupView() {
emailTextField.backgroundColor = .init(white: 0, alpha: 0.03)
passwordTextField.backgroundColor = .init(white: 0, alpha: 0.03)
loginButton.layer.cornerRadius = 5
let attributedText = NSMutableAttributedString(string: "Don't have an account? ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14),
NSAttributedString.Key.foregroundColor: UIColor.lightGray.cgColor])
attributedText.append(NSAttributedString(string: "SignUp", attributes: [NSAttributedString.Key.foregroundColor: UIColor.rgbColor(red: 17, green: 154, blue: 237, alpha: 1).cgColor,
NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14)]))
dontHaveAccountButton.setAttributedTitle(attributedText, for: .normal)
emailTextField.addTarget(self, action: #selector(handleTextInputChange), for: .editingChanged)
passwordTextField.addTarget(self, action: #selector(handleTextInputChange), for: .editingChanged)
loginButton.addTarget(self, action: #selector(handleLogin), for: .touchUpInside)
}
@objc func handleLogin() {
guard let email = emailTextField.text else { return }
guard let password = passwordTextField.text else { return }
Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
if let error = error {
print("Failed to sign in with email:", error)
return
}
print("Successfullu logged back in with user:", result?.user.uid ?? "")
UIApplication.mainTabBarController()?.setupViewControllers()
self.dismiss(animated: true, completion: nil)
}
}
@objc func handleTextInputChange() {
let isFormValid = emailTextField.text?.count ?? 0 > 0 && passwordTextField.text?.count ?? 0 > 0
if isFormValid {
loginButton.backgroundColor = .rgbColor(red: 17, green: 154, blue: 237, alpha: 1)
loginButton.isEnabled = true
} else {
loginButton.backgroundColor = .rgbColor(red: 149, green: 204, blue: 244, alpha: 1)
loginButton.isEnabled = false
}
}
@IBAction func handleShowSignUp(_ sender: Any) {
let signUpController: SignUpController = .init()
signUpController.modalPresentationStyle = .fullScreen
navigationController?.pushViewController(signUpController, animated: true)
}
}
|
public class GildedRose {
var items:[Item]
public init(items:[Item]) {
self.items = items
}
public func updateQuality() {
items.forEach { item in
if !item.isAgedBrie, !item.isBackstagePass {
if !item.isSulfuras {
item.setQuality(by: .decreasing)
}
} else {
item.setQuality(by: .increasing)
if item.isBackstagePass {
if (item.sellIn < 11) {
item.setQuality(by: .increasing)
}
if (item.sellIn < 6) {
item.setQuality(by: .increasing)
}
}
}
if !item.isSulfuras {
item.sellIn = item.sellIn - 1
}
if item.sellIn < 0 {
if !item.isAgedBrie {
if !item.isBackstagePass {
if !item.isSulfuras {
item.setQuality(by: .decreasing)
}
} else {
item.setQuality(by: .zero)
}
} else {
item.setQuality(by: .increasing)
}
}
}
}
}
|
//
// LeBaluchon.swift
// Le BaluchonTests
//
// Created by jullianm on 27/11/2017.
// Copyright © 2017 jullianm. All rights reserved.
//
import XCTest
@testable import Le_Baluchon
class LeBaluchon: XCTestCase {
var currencyRequest: CurrencyRatesRequest!
var translationRequest: TranslationRequest!
override func setUp() {
super.setUp()
currencyRequest = CurrencyRatesRequest()
translationRequest = TranslationRequest()
}
override func tearDown() {
super.tearDown()
currencyRequest = nil
translationRequest = nil
}
func testJSONCurrencyRequest() {
// where
currencyRequest.currencyToConvert = "25,10"
// when
currencyRequest.getCurrencyExchangeRates()
// then
guard let resultToTest = currencyRequest.result else { return }
XCTAssertEqual(resultToTest > 25.10 || resultToTest < 25.10 , true , "API Request not working")
}
func testJSONTranslationRequest() {
// where
translationRequest.textToTranslate = "Bonjour tu vas bien ?"
// when
translationRequest.getGoogleTranslation()
// then
guard let translationOutput = translationRequest.translationOutput else { return }
XCTAssertEqual(translationOutput, "Hello, how are you doing ?" , "API Request not working")
}
func testJSONWeatherRequest() {
// where
var weatherInfos: [WeatherCast]?
// when
WeatherRequest.getWeatherCast(completion: { (weathercast) in
weatherInfos = weathercast
})
// then
guard let weatherData = weatherInfos else { return }
XCTAssertEqual(weatherData[0].name, "TEST" , "API Request not working")
XCTAssertEqual(weatherData[1].name, "New York" , "API Request not working")
XCTAssertEqual(weatherData[2].name, "Chicago" , "API Request not working")
XCTAssertEqual(weatherData[3].name, "Philadelphia" , "API Request not working")
}
}
|
//
// ZGModel.swift
// ZGUIDemo
//
//
import UIKit
import ZGNetwork
open class ZGModel {
//用于pv打点, 任意取一个设置了statistic_AnalysisData的item
public var pageViewItem:ZGBaseUIItem?
open var items : [Any]
open var sections : [ZGCollectionReusableViewItem]
open var pageSize : Int = 20
open var pageNumber : Int = 1
open var loading : Bool = false
open var hasNext : Bool = false
open var didFinishLoad: Bool = false
open var pageSourceType : String?
open var listVersion : String?
open var visibleRect : CGRect?
public init() {
self.items = []
self.sections = []
}
public func resetPageViewItem(_ item:ZGBaseUIItem) {
}
/// 设置item索引
///
open func resetItemsIndex() {
var modelIndex:Int = 0
var itemIndex:Int = 0
for item in self.items {
if item is [Any] {
modelIndex += 1
itemIndex = 0
let arr = item as! [Any]
for item1 in arr {
if item1 is ZGBaseUIItem {
itemIndex += 1
let uiItem = item1 as! ZGBaseUIItem
uiItem.itemIndex = itemIndex
uiItem.modelIndex = modelIndex
self.resetPageViewItem(uiItem)
}
}
} else if item is ZGBaseUIItem {
itemIndex += 1
let uiItem = item as! ZGBaseUIItem
uiItem.itemIndex = itemIndex
uiItem.modelIndex = modelIndex
self.resetPageViewItem(uiItem)
}
}
}
open func loadItems(_ parameters : [String:Any]? = nil,
completion : @escaping ([String:Any]?)->Void ,
failure : @escaping (ZGNetworkError)->Void){
}
}
|
//
// FirebaseDatabase.swift
// PansChat2
//
// Created by Jakub Iwaszek on 30/09/2020.
//
import Foundation
import Firebase
class FirebaseDatabase {
static let shared = FirebaseDatabase()
var ref: DatabaseReference! = Database.database().reference()
var storageRef = Storage.storage().reference()
func getUserData(userId: String,completion: @escaping (User?) -> Void) {
ref.child("users").child(userId).observeSingleEvent(of: .value) { (snapshot) in
if let dataDict = snapshot.value as? NSDictionary {
guard let email = dataDict["email"] as? String else {
print("error email parsing")
return
}
let user = User(id: userId, email: email)
completion(user)
} else {
completion(nil)
}
}
}
func getAllUsers(completion: @escaping ([User]?) -> Void) {
guard let currentUser = Auth.auth().currentUser else { return }
var users: [User] = []
ref.child("users").observeSingleEvent(of: .value) { (snapshot) in
for child in snapshot.children {
guard let childSnapshot = child as? DataSnapshot else { return }
if let childValue = childSnapshot.value as? NSDictionary {
let id = childValue["id"] as! String
if id != currentUser.uid {
let email = childValue["email"] as! String
let user = User(id: id, email: email)
users.append(user)
}
}
}
completion(users)
}
}
func addUserToCurrentUserFriendList(user: User, completion: @escaping (Bool) -> Void) { //bez completion?
guard let currentUser = Auth.auth().currentUser else { return }
ref.child("users").child(currentUser.uid).child("friends").updateChildValues([user.id : user.id])
}
func getUserFriends(user: User, completion: @escaping ([User]?) -> Void) {
var group = DispatchGroup()
var friends: [User] = []
ref.child("users").child(user.id).child("friends").observeSingleEvent(of: .value) { (snapshot) in
for child in snapshot.children {
guard let childSnapshot = child as? DataSnapshot else { return }
group.enter()
let id = childSnapshot.key
self.getUserData(userId: id) { (user) in
guard let user = user else { return }
friends.append(user)
group.leave()
}
}
group.notify(queue: .main) {
completion(friends)
}
}
}
func sendPhotoToUsers(fromUser: User, toUsers: [Int:User], photoData: Data, completion: @escaping (Bool) -> Void) {
/*let string = photoData.base64EncodedString()
let data = Data(base64Encoded: string)*/
let generatedPhotoID = UUID().uuidString
//uzyc firebase storage i przechowywac jako img - uzywac reference
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
//metadata.customMetadata = ["from": fromUser.id, "to": (toUsers.first?.value.id)!] //przerobic na wielu userow FOR?
storageRef.child(generatedPhotoID).putData(photoData, metadata: nil) { (metadata, err) in
guard let metadata = metadata else {
print("metadata storage error")
completion(false)
return
}
completion(true)
}
ref.child("photos").child(generatedPhotoID).updateChildValues(["from": fromUser.id])
for toUser in toUsers {
ref.child("photos").child(generatedPhotoID).child("to").updateChildValues([toUser.value.id:toUser.value.id])
}
}
func downloadPhotos(for user: User, completion: @escaping ([Photo]) -> Void) {
var fromUsersPhotoDict: [Photo] = []
ref.child("photos").observeSingleEvent(of: .value) { (snapshot) in
let children = snapshot.children
for child in children {
guard let childSnapshot = child as? DataSnapshot else { return }
if let valueDict = childSnapshot.value as? NSDictionary {
let idFrom = valueDict["from"] as! String
guard let idToDict = valueDict["to"] as? NSDictionary else { return }
for idToChild in idToDict {
let idToString = idToChild.key as! String
if user.id == idToString {
let photo = Photo(id: childSnapshot.key, fromUserId: idFrom, toUserId: idToString)
fromUsersPhotoDict.append(photo)
}
}
}
}
completion(fromUsersPhotoDict)
}
}
func getPhoto(photoId: String, completion: @escaping ([String:Any]) -> Void) {
var photoInfo: [String: Any] = [:]
var group = DispatchGroup()
group.enter()
storageRef.child(photoId).getData(maxSize: 1 * 1024 * 1024) { (data, error) in
if error != nil {
print("error while gathering photo data")
} else {
guard let data = data else { /*completion nil*/return }
photoInfo.updateValue(data, forKey: "photoData")
group.leave()
}
}
group.enter()
storageRef.child(photoId).getMetadata { (metadata, error) in
if error != nil {
print("error while gathering photo metadata")
} else {
guard let date = metadata?.timeCreated else { return }
photoInfo.updateValue(date, forKey: "timeCreated")
group.leave()
}
}
group.notify(queue: .main) {
completion(photoInfo)
}
}
func removeSeenPhotoFromUser(userId: String, photoId: String) {
ref.child("photos").child(photoId).child("to").child(userId).removeValue { (error, childref) in
if error != nil {
print(error?.localizedDescription)
} else {
print("removed")
childref.parent?.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChildren() {
print("true")
} else {
print("false")
self.ref.child("photos").child(photoId).removeValue()
self.removePhotoFromStorage(photoId: photoId)
}
})
}
}
}
func removePhotoFromStorage(photoId: String) {
storageRef.child(photoId).delete { (error) in
if error != nil {
print(error?.localizedDescription)
}
}
}
}
|
//
// URLSession+Extension.swift
// ParisWeather
//
// Created by Xav Mac on 07/03/2020.
// Copyright © 2020 ParisWeather. All rights reserved.
//
import Foundation
extension URLSession: NetworkSession {
func performRequest(urlRequest: URLRequest,
completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
let method = urlRequest.httpMethod ?? "undisclosed method"
print("ℹ️ Request made to URL: \(urlRequest) (\(method)) ℹ️")
let task = dataTask(with: urlRequest) { data, response, error in
completion(data, response, error)
}
task.resume()
}
}
|
//
// ViewController2.swift
// schoolCountdownApp
//
// Created by Brian on 10/31/16.
// Copyright © 2016 WAINOM. All rights reserved.
//
import UIKit
class ViewController2: UIViewController {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var markerLabel: UILabel!
let formatter = NSDateFormatter()
let userCalendar = NSCalendar.currentCalendar()
let requestedComponent: NSCalendarUnit = [
NSCalendarUnit.Month,
NSCalendarUnit.Day,
NSCalendarUnit.Hour,
NSCalendarUnit.Minute,
NSCalendarUnit.Second
]
override func viewDidLoad() {
super.viewDidLoad()
self.markerLabel.text = "Until Finals :("
// Do any additional setup after loading the view.
let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(printTime), userInfo: nil, repeats: true)
timer.fire()
}
func printTime(){
formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
let startTime = NSDate()
let endTime = formatter.dateFromString("5/30/17 12:00:00 a")
let timeDifference = userCalendar.components(requestedComponent, fromDate: startTime, toDate:endTime!, options: [])
dateLabel.text = "\(timeDifference.month) Months \(timeDifference.day) Days \(timeDifference.minute) Minutes \(timeDifference.second) Seconds"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// Questions.swift
// Game Quiz
//
// Created by Илья Карась on 05/05/2019.
// Copyright © 2019 Ilia Karas. All rights reserved.
//
struct Question {
var text: String
var type: ResponseType
var answers: [Answer]
}
extension Question {
static func loadData() -> [Question] {
return [
Question(
text: "Please, input your age.",
type: .texted,
answers: [
Answer(text: "", userAge: 0)
]
),
Question(
text: "Which platform do you want to play?",
type: .singlePlatform,
answers: [
Answer(text: "Personal computer", platform: .pc),
Answer(text: "PlayStation 4", platform: .ps4),
Answer(text: "XBoxOne", platform: .xbox),
Answer(text: "iOS devices", platform: .iOS),
]
),
Question(
text: "How important is the visual component for you?",
type: .rangedGraphic,
answers: [
Answer(text: "Absolutely not important", graphicRating: (0..<0.2)),
Answer(text: "Almost unimportant", graphicRating: (0.2..<0.4)),
Answer(text: "Little important", graphicRating: (0.4..<0.6)),
Answer(text: "Important", graphicRating: (0.6..<0.8)),
Answer(text: "Very important", graphicRating: (0.8..<1.1))
]
),
Question(
text: "How important is the story to you?",
type: .rangedStory,
answers: [
Answer(text: "Absolutely not important", storyRating: (0..<0.2)),
Answer(text: "Almost unimportant", storyRating: (0.2..<0.4)),
Answer(text: "Little important", storyRating: (0.4..<0.6)),
Answer(text: "Important", storyRating: (0.6..<0.8)),
Answer(text: "Very important", storyRating: (0.8..<1.1))
]
),
Question(
text: "Do you like to overcome difficulties?",
type: .rangedDifficulty,
answers: [
Answer(text: "Definitely not!", difficultyRating: (0..<0.2)),
Answer(text: "I do not like", difficultyRating: (0.2..<0.4)),
Answer(text: "I like", difficultyRating: (0.4..<0.6)),
Answer(text: "I really like", difficultyRating: (0.6..<0.8)),
Answer(text: "The harder the better!", difficultyRating: (0.8..<1.1))
]
),
Question(
text: "Select your favorite genres",
type: .multipleGenre,
answers: [
Answer(text: "RPG", genre: .rpg),
Answer(text: "Action", genre: .action),
Answer(text: "Sport", genre: .sport),
Answer(text: "Shooter", genre: .shooter),
Answer(text: "Race", genre: .race),
Answer(text: "Strategy", genre: .strategy),
Answer(text: "Quest", genre: .quest),
Answer(text: "Stealth", genre: .stealth),
Answer(text: "Simulator", genre: .simulator),
Answer(text: "Horror", genre: .horror),
Answer(text: "Slasher", genre: .slasher),
Answer(text: "Adventure", genre: .adventure)
]
),
]
}
}
|
import UIKit
// Properties
class ExampleClass {
var property1: Int = 0
var property2: String = ""
let constProperty: Int = 20
}
var ec = ExampleClass()
ec.property1
ec.property2
ec.constProperty
// Fails (Constant can not modied) => ec.constProperty = 20
struct Example2 {
var name: String = "Jorge"
var age: Int = 20
// Computed Properties
var userInfo: String {
get {
return "My name is \(name) and I am \(age) years old"
}
}
}
var e2 = Example2()
e2.userInfo
// Property Observable
class Company {
var employeeNumber: Int = 0 {
willSet {
print("The employee number was \(employeeNumber) and the new employee numbers will be \(newValue)")
}
didSet {
print("Employee number was \(oldValue). After calling the set function, the new employee number is \(employeeNumber)")
}
}
}
var c = Company()
c.employeeNumber = 30 |
//
// CellManagerContainer.swift
// OSOM_app
//
// Created by Miłosz Bugla on 18/07/2017.
// Copyright © 2017 ITEO Sp. z o.o. All rights reserved.
//
import Foundation
class CellManagerContainer {
}
|
import XCTest
import SwiftCheck
import Bow
import BowOptics
import BowOpticsLaws
import BowLaws
class AffineTraversalTest: XCTestCase {
func testAffineTraversalLaws() {
AffineTraversalLaws.check(affineTraversal: AffineTraversal<String, String>.identity)
}
func testSetterLaws() {
SetterLaws.check(setter: AffineTraversal<String, String>.identity.asSetter)
}
func testTraversalLaws() {
TraversalLaws.check(traversal: AffineTraversal<String, String>.identity.asTraversal)
}
func testAffineTraversalAsFold() {
property("AffineTraversal as Fold: size") <~ forAll { (ints: Array<Int>) in
return SumType.optionalHead.asFold.size(ints) == Option.fix(Option.fromOptional(ints.first).map(constant(1))).getOrElse(0)
}
property("AffineTraversal as Fold: nonEmpty") <~ forAll { (ints: Array<Int>) in
return SumType.optionalHead.asFold.nonEmpty(ints) == Option.fromOptional(ints.first).isDefined
}
property("AffineTraversal as Fold: isEmpty") <~ forAll { (ints: Array<Int>) in
return SumType.optionalHead.asFold.isEmpty(ints) == Option.fromOptional(ints.first).isEmpty
}
property("AffineTraversal as Fold: getAll") <~ forAll { (ints: Array<Int>) in
return SumType.optionalHead.asFold.getAll(ints) ==
Option.fromOptional(ints.first).toArray().k()
}
property("AffineTraversal as Fold: combineAll") <~ forAll { (ints: Array<Int>) in
return SumType.optionalHead.asFold.combineAll(ints) == Option.fromOptional(ints.first).fold(constant(Int.empty()), id)
}
property("AffineTraversal as Fold: fold") <~ forAll { (ints: Array<Int>) in
return SumType.optionalHead.asFold.fold(ints) == Option.fromOptional(ints.first).fold(constant(Int.empty()), id)
}
property("AffineTraversal as Fold: headOption") <~ forAll { (ints: Array<Int>) in
return SumType.optionalHead.asFold.headOption(ints) ==
Option.fromOptional(ints.first)
}
property("AffineTraversal as Fold: lastOption") <~ forAll { (ints: Array<Int>) in
return SumType.optionalHead.asFold.lastOption(ints) ==
Option.fromOptional(ints.first)
}
}
func testAffineTraversalProperties() {
property("void should always return none") <~ forAll { (value: String) in
let void = AffineTraversal<String, Int>.void
return void.getOption(value) == Option<Int>.none()
}
property("void should return source when setting target") <~ forAll { (str: String, int: Int) in
let void = AffineTraversal<String, Int>.void
return void.set(str, int) == str
}
property("Checking if there is no target") <~ forAll { (ints: Array<Int>) in
return SumType.optionalHead.nonEmpty(ints) == !ints.isEmpty
}
property("Checking if a target exists") <~ forAll { (ints: Array<Int>) in
return SumType.optionalHead.isEmpty(ints) == ints.isEmpty
}
property("lift should be consistent with modify") <~ forAll { (ints: Array<Int>, f: ArrowOf<Int, Int>) in
return SumType.optionalHead.lift(f.getArrow)(ints) == SumType.optionalHead.modify(ints, f.getArrow)
}
property("liftF should be consistent with modifyF") <~ forAll { (ints: Array<Int>, f: ArrowOf<Int, Int>) in
let g = f.getArrow >>> Try.pure
return SumType.optionalHead.liftF(g)(ints) ==
SumType.optionalHead.modifyF(ints, g)
}
property("Finding a target using a predicate should be wrapped in the correct option result") <~ forAll { (ints: Array<Int>, predicate: Bool) in
return SumType.optionalHead.find(ints, constant(predicate)).fold(constant(false), constant(true)) == predicate || ints.isEmpty
}
property("Checking existence predicate over the target should result in same result as predicate") <~ forAll { (ints: Array<Int>, predicate: Bool) in
return SumType.optionalHead.exists(ints, constant(predicate)) == predicate || ints.isEmpty
}
property("Checking satisfaction of predicate over the target should result in opposite result as predicate") <~ forAll { (ints: Array<Int>, predicate: Bool) in
return SumType.optionalHead.all(ints, constant(predicate)) == predicate || ints.isEmpty
}
property("Joining two optionals together with same target should yield same result") <~ forAll { (int: Int) in
let joinedOptional = SumType.optionalHead.choice(SumType.defaultHead)
return joinedOptional.getOption(Either.left([int])) == joinedOptional.getOption(Either.right(int))
}
}
func testAffineTraversalComposition() {
property("AffineTraversal + AffineTraversal::identity") <~ forAll { (array: Array<Int>, def: Int) in
return (SumType.optionalHead + AffineTraversal<Int, Int>.identity).getOption(array).getOrElse(def) == SumType.optionalHead.getOption(array).getOrElse(def)
}
property("AffineTraversal + Iso::identity") <~ forAll { (array: Array<Int>, def: Int) in
return (SumType.optionalHead + Iso<Int, Int>.identity).getOption(array).getOrElse(def) == SumType.optionalHead.getOption(array).getOrElse(def)
}
property("AffineTraversal + Lens::identity") <~ forAll { (array: Array<Int>, def: Int) in
return (SumType.optionalHead + Lens<Int, Int>.identity).getOption(array).getOrElse(def) == SumType.optionalHead.getOption(array).getOrElse(def)
}
property("AffineTraversal + Prism::identity") <~ forAll { (array: Array<Int>, def: Int) in
return (SumType.optionalHead + Prism<Int, Int>.identity).getOption(array).getOrElse(def) == SumType.optionalHead.getOption(array).getOrElse(def)
}
property("AffineTraversal + Getter::identity") <~ forAll { (array: Array<Int>) in
return (SumType.optionalHead + Getter<Int, Int>.identity).getAll(array).asArray == SumType.optionalHead.getOption(array).fold(constant([]), { x in [x] })
}
let nonEmptyGenerator = Array<Int>.arbitrary.suchThat { array in array.count > 0 }
property("AffineTraversal + Setter::identity") <~ forAll(nonEmptyGenerator, Int.arbitrary) { (array: Array<Int>, def: Int) in
return (SumType.optionalHead + Setter<Int, Int>.identity).set(array, def) == SumType.optionalHead.set(array, def)
}
property("AffineTraversal + Fold::identity") <~ forAll { (array: Array<Int>) in
return (SumType.optionalHead + Fold<Int, Int>.identity).getAll(array).asArray == SumType.optionalHead.getOption(array).fold(constant([]), { x in [x] })
}
property("AffineTraversal + Traversal::identity") <~ forAll { (array: Array<Int>) in
return (SumType.optionalHead + Traversal<Int, Int>.identity).getAll(array).asArray == SumType.optionalHead.getOption(array).fold(constant([]), { x in [x] })
}
}
}
|
import Foundation
/*
Q061. Rotate List
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
*/
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
func reverse(_ head: ListNode?) -> ListNode? {
var current = head, previous: ListNode? = nil
while current != nil {
let next = current?.next
current?.next = previous
previous = current
current = next
}
return previous
}
func printList(_ name:String, head: ListNode?) {
var string = ""
var start: ListNode? = head
while start != nil {
if let startEnd = start {
string += String(" -> \(startEnd.val)")
start = startEnd.next
}
}
print("\(name) \(string)")
}
let headNode = ListNode(1)
let secondNode = ListNode(2)
let thirdNode = ListNode(3)
let fouthNode = ListNode(4)
let fifthNode = ListNode(5)
let sixthNode = ListNode(6)
headNode.next = secondNode
//secondNode.next = thirdNode
//thirdNode.next = fouthNode
//fouthNode.next = fifthNode
//fifthNode.next = sixthNode
/*
Input: -> 1 -> 2 -> 3 -> 4 -> 5 -> 6, k = 2
Expected: -> 5 -> 6 -> 1 -> 2 -> 3 -> 4
1. traverse the list to get the length, save the oldEnd node
2. calculate k % length, to find the newEnd node by shift length - k % length - 1
3. newEnd->next should be the new head
4. make oldEnd->next = oldHead
5. newEnd->next = nil
*/
func rotateRight(_ head: ListNode?, _ k: Int) -> ListNode? {
guard head != nil else { return head }
var length = 1
var oldEnd = head
while oldEnd?.next != nil {
oldEnd = oldEnd?.next
length += 1
}
if length < 2 {
return head
}
let shift = k % length
if shift == 0 {
return head
}
var newEnd = head
var i = 1
while i < length - shift {
i += 1
newEnd = newEnd?.next
}
let newHead = newEnd?.next
oldEnd?.next = head
newEnd?.next = nil
return newHead
}
printList("RESULT", head: rotateRight(headNode, 1))
|
//
// AppDelegate.swift
// photopizza
//
// Created by Gary Cheng on 7/9/16.
// Copyright © 2016 Gary Cheng. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKShareKit
import FBSDKLoginKit
import Firebase
import FirebaseAuth
import SwiftyJSON
var currentUser : User = User()
var ref: FIRDatabaseReference? = nil
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
override init() {
FIRApp.configure()
FIRDatabase.database().persistenceEnabled = true
ref = FIRDatabase.database().reference()
ref!.keepSynced(true)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch. UIApplication.sharedApplication().statusBarStyle = .LightContent
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
print("access token1: \(FBSDKAccessToken.currentAccessToken()) ")
if (FBSDKAccessToken.currentAccessToken() != nil) {
verifyAndLaunch(FBSDKAccessToken.currentAccessToken())
}
else {
self.goToView("loginPage")
print("firebase error 1")
}
return true
}
func verifyAndLaunch(fbToken: FBSDKAccessToken) {
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(fbToken.tokenString)
print("authData:")
if let user: FIRUser? = FIRAuth.auth()?.currentUser {
print("user signed in")
self.getUserDataAndSwitchViews(user, view: "newNav")
} else {
print("user not signed in")
FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in
if (error != nil) {
print("FIREBASE SIGN IN ERROR") }
else {
print("firebase sign in working")
self.getUserDataAndSwitchViews(user, view: "newNav")
}
}
}
}
func getUserDataAndSwitchViews(user: FIRUser?, view: String) {
if let userRef: FIRDatabaseReference? = FIRDatabase.database().reference().child("users").child(user!.uid) {
userRef!.observeSingleEventOfType(.Value,
withBlock: { snapshot in
let userInfo = JSON(snapshot.value!)
let userName = userInfo["userName"].stringValue
let userFacebookId = userInfo["facebookId"].intValue
let userEmail = userInfo["userEmail"].stringValue
let userFirebaseId = userInfo["firebaseId"].stringValue
var groups = [String:String]()
currentUser = User(name: userName, email: userEmail, facebookId: userFacebookId, groups: groups)
currentUser.firebaseId = userFirebaseId
self.goToView(view)
}
)
} else {
print("failed to sign in to firebase")
}
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an inc oming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
let loginManager: FBSDKLoginManager = FBSDKLoginManager()
loginManager.logOut()
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool
{
return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
func goToView(view: String) {
let storyBoard : UIStoryboard? = UIStoryboard(name: "Main", bundle: nil)
let nextViewController = (storyBoard?.instantiateViewControllerWithIdentifier(view))! as UIViewController
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.rootViewController = nextViewController
self.window?.makeKeyAndVisible()
}
}
|
//
// WahooAdvancedFitnessMachineService.swift
// SwiftySensorsTrainers iOS
//
// Created by Josh Levine on 5/9/18.
// Copyright © 2018 Kinetic. All rights reserved.
//
import CoreBluetooth
import SwiftySensors
import Signals
open class WahooAdvancedFitnessMachineService: Service, ServiceProtocol {
public static var uuid: String { return "A026EE0B-0A7D-4AB3-97FA-F1500F9FEB8B" }
public static var characteristicTypes: Dictionary<String, Characteristic.Type> = [
WahooAdvancedTrainerControlPoint.uuid: WahooAdvancedTrainerControlPoint.self
]
public var controlPoint: WahooAdvancedTrainerControlPoint? { return characteristic() }
open class WahooAdvancedTrainerControlPoint: Characteristic {
public static var uuid: String { return "A026E037-0A7D-4AB3-97FA-F1500F9FEB8B" }
required public init(service: Service, cbc: CBCharacteristic) {
super.init(service: service, cbc: cbc)
cbCharacteristic.notify(true)
}
}
open func getHubHeight() {
let command = WahooAdvancedFitnessMachineSerializer.getHubHeight()
controlPoint?.cbCharacteristic.write(command.data, writeType: .withoutResponse)
}
open func setHubHeight(millimeters: Int) {
let command = WahooAdvancedFitnessMachineSerializer.setHubHeight(millimeters: UInt16(millimeters))
controlPoint?.cbCharacteristic.write(command.data, writeType: .withoutResponse)
}
open func getWheelBase() {
let command = WahooAdvancedFitnessMachineSerializer.getHubHeight()
controlPoint?.cbCharacteristic.write(command.data, writeType: .withoutResponse)
}
open func setWheelBase(millimeters: Int) {
let command = WahooAdvancedFitnessMachineSerializer.setWheelBase(millimeters: UInt16(millimeters))
controlPoint?.cbCharacteristic.write(command.data, writeType: .withoutResponse)
}
open func getTargetTilt() {
let command = WahooAdvancedFitnessMachineSerializer.getTargetTilt()
controlPoint?.cbCharacteristic.write(command.data, writeType: .withoutResponse)
}
open func setTargetTilt(grade: Double) {
let command = WahooAdvancedFitnessMachineSerializer.setTargetTilt(grade: grade)
controlPoint?.cbCharacteristic.write(command.data, writeType: .withoutResponse)
}
open func getTiltMode() {
let command = WahooAdvancedFitnessMachineSerializer.getTiltMode()
controlPoint?.cbCharacteristic.write(command.data, writeType: .withoutResponse)
}
open func getTiltLimits() {
let command = WahooAdvancedFitnessMachineSerializer.getTiltLimits()
controlPoint?.cbCharacteristic.write(command.data, writeType: .withoutResponse)
}
}
|
//
// Date+Extension.swift
// AccountBook
//
// Created by Mason Sun on 2019/11/23.
// Copyright © 2019 Mason Sun. All rights reserved.
//
import Foundation
extension Calendar {
static var currentMonth: Int {
return Calendar.current.component(.month, from: Date())
}
static var currentYear: Int {
return Calendar.current.component(.year, from: Date())
}
static var years: [Int] {
let beginYear = Calendar.current.component(.year, from: Date.init(timeIntervalSince1970: 0))
return (beginYear...currentYear).reversed().map { $0 }
}
static var dateClosedRange: ClosedRange<Date> {
let min = Calendar.current.date(byAdding: .year, value: -70, to: Date())!
let max = Calendar.current.date(byAdding: .month, value: 1, to: Date())!
return min...max
}
}
extension Date {
var displayWeakFormat: String {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM d EEE"
return formatter.string(from: self)
}
var displayYearFormat: String {
let formatter = DateFormatter()
formatter.dateFormat = "MMM yyyy"
return formatter.string(from: self)
}
static var currentTimeInterval: TimeInterval {
return Date().timeIntervalSince1970
}
func isSameDay(with date: Date) -> Bool {
return Calendar.current.isDate(self, inSameDayAs: date)
}
func compare(with date: Date) -> Int {
return Calendar.current.compare(date, to: self, toGranularity: .day).rawValue
}
func add(component: Calendar.Component, value: Int) -> Date? {
return Calendar.current.date(byAdding: component, value: value, to: self)
}
}
|
//
// StringExtension.swift
// florafinder
//
// Created by Andrew Tokeley on 3/02/16.
// Copyright © 2016 Andrew Tokeley . All rights reserved.
//
import Foundation
extension String
{
func numberOfMatches(searchText: String) -> Int
{
do
{
let regEx = try NSRegularExpression(pattern: searchText, options: NSRegularExpressionOptions.CaseInsensitive)
let matches = regEx.numberOfMatchesInString(self, options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0, self.characters.count))
return matches
}
catch
{
return 0
}
}
func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat
{
var adjustedWidth = width
adjustedWidth *= (25/(adjustedWidth+2)+1);
let constraintRect = CGSize(width: adjustedWidth, height: CGFloat.max)
let boundingBox = self.boundingRectWithSize(constraintRect, options: [.UsesDeviceMetrics, .UsesLineFragmentOrigin], attributes: [NSFontAttributeName: font], context: nil)
return boundingBox.height
}
} |
import SwiftUI
@available(OSX 10.15, *)
public struct GreenView: View {
public init() {
}
public var body: some View {
Color.green
}
}
#if os(macOS)
#else
@available(tvOS 13.0, iOS 13.0, *)
public struct ActivityIndicatorView: UIViewRepresentable {
@Binding public var animating: Bool
public let style: UIActivityIndicatorView.Style
public func makeUIView(context: Context) -> UIActivityIndicatorView {
let view = UIActivityIndicatorView()
view.style = self.style
return view
}
public func updateUIView(_ uiView: UIViewType, context: Context) {
if animating {
uiView.startAnimating()
} else {
uiView.stopAnimating()
}
}
}
#endif
|
//
// CameraOptions.swift
// yourservice-ios
//
// Created by Игорь Сорокин on 29.10.2020.
// Copyright © 2020 spider. All rights reserved.
//
import Foundation
struct CameraOptions: OptionSet {
let rawValue: UInt8
static let photo = CameraOptions(rawValue: 1 << 0)
static let video = CameraOptions(rawValue: 1 << 1)
var isPhotoOnly: Bool {
rawValue == (1 << 0)
}
var isVideoOnly: Bool {
rawValue == (1 << 1)
}
}
|
//
// Post.swift
// DogFound
//
// Created by Peter Zaporowski on 18.03.2017.
// Copyright © 2017 Peter Zaporowski. All rights reserved.
//
import Foundation
class Post: NSObject, NSCoding {
private var _imagePath: String!
private var _title: String!
private var _postDesc: String! // using var description can override the class Description
var imagePath: String {
return _imagePath
}
var title: String {
return _title
}
var postDesc: String {
return _postDesc
}
init(imagePath: String, title: String, description: String){
self._imagePath = imagePath
self._title = title
self._postDesc = description
}
override init(){
}
//////Coders and decoders (Objective-C)
required convenience init?(coder aDecoder: NSCoder){
self.init()
self._imagePath = aDecoder.decodeObjectForKey("imagePath") as? String
self._title = aDecoder.decodeObjectForKey("title") as? String
self._postDesc = aDecoder.decodeObjectForKey("description") as? String
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self._imagePath, forKey: "imagePath")
aCoder.encodeObject(self._title, forKey: "title")
aCoder.encodeObject(self._postDesc, forKey: "description")
}
///End of coders and decoders :)
}
|
//
// URLQueryDataAdapter.swift
// BotanicalGarden
//
// Created by 黃偉勛 Terry on 2021/4/18.
//
import Foundation
struct URLQueryDataAdapter: RequestAdapter {
let parameters: [String: Any]
func adapted(request: URLRequest) throws -> URLRequest {
guard let url = request.url else {
throw NetworkingError.Request.missingURL
}
var req = request
let finalURL = encoded(url: url)
req.url = finalURL
return req
}
private func encoded(url: URL) -> URL {
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { return url }
components.queryItems = parameters.map {
URLQueryItem(name: $0.key, value: $0.value as? String)
}
return components.url ?? url
}
}
|
//
// UIScrollViewExtension.swift
// StickyHeader
//
// Created by Yannick Heinrich on 25.08.16.
// Copyright © 2016 yageek. All rights reserved.
//
import UIKit
import ObjectiveC
private var xoStickyHeaderKey: UInt8 = 0
public extension UIScrollView {
var stickyHeader: StickyHeader! {
var header = objc_getAssociatedObject(self, &xoStickyHeaderKey) as? StickyHeader
if header == nil {
header = StickyHeader()
header!.scrollView = self
objc_setAssociatedObject(self, &xoStickyHeaderKey, header, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return header!
}
}
|
struct Address: Equatable {
let raw: String
let domain: String?
init(raw: String, domain: String? = nil) {
self.raw = raw.trimmingCharacters(in: .whitespacesAndNewlines)
self.domain = domain?.trimmingCharacters(in: .whitespacesAndNewlines)
}
var title: String {
domain ?? raw
}
static func ==(lhs: Address, rhs: Address) -> Bool {
lhs.raw == rhs.raw &&
lhs.domain == rhs.domain
}
}
|
//
// Settings.swift
// Mercury
//
// Created by toco on 22/01/17.
// Copyright © 2017 tocozakura. All rights reserved.
//
import Foundation
import UIKit
enum Settings {
enum Size {
static let collectionCellSize = CGSize(width: 150.0, height: 200.0)
static let roomTableViewCellSize: CGFloat = 80.0
}
enum Color {
static let hogeColor = UIColor.black
static let mercuryColor = UIColor(red:0.92, green:0.21, blue:0.18, alpha:1.00)
}
}
|
//
// ViewController.swift
// CatumblrMac
//
// Created by gleb on 11/21/14.
// Copyright (c) 2014 gleb. All rights reserved.
//
import Cocoa
import Alamofire
import SwiftyJSON
class ViewController: NSViewController {
@IBOutlet weak var TempLabel: NSTextField!
@IBOutlet weak var BlogCaption: NSTextField!
@IBOutlet weak var Preview: NSImageView!
var weather_string : NSString = "+0"
var im_path = NSURL.init(string : "")
let weatherRequest : URLStringConvertible = "http://www.myweather2.com/developer/forecast.ashx?uac=pP9Pz3soUU&output=json&query=%2049.425267,%2032.063599&temp_unit=c"
override func viewDidLoad() {
super.viewDidLoad()
self.getWeather()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
func getWeather () -> ()
{
Alamofire.request(.GET, weatherRequest, parameters: ["":""])
.response { (request, response, data, error) in
println(request)
println(response)
println(data)
println(error)
//let json : JSON =
}
.responseString { (_, _, text, _) in
println(text)
//let json = JSON(data: text)
}
.responseJSON { (req, res, text, error) in
if(error != nil) {
NSLog("Error: \(error)")
println(req)
println(res)
}
else {
var weather_json = JSON(text!)
println(text)
println(weather_json)
println(weather_json["weather"]["curren_weather"][0]["weather_text"])
self.weather_string = weather_json["weather"]["curren_weather"][0]["temp"].string! + " " + weather_json["weather"]["curren_weather"][0]["weather_text"].string!
self.TempLabel.stringValue = self.weather_string
}
}
}
@IBAction func ImageSelected(sender: AnyObject) {
let panel = NSOpenPanel() as NSOpenPanel
panel.canChooseDirectories = false
panel.canChooseFiles = true
panel.canCreateDirectories = false
panel.beginWithCompletionHandler({ (res: NSInteger) in
println("dsfsadf")
println(panel.URL)
self.im_path = panel.URL!
let im = NSImage.init(byReferencingURL: panel.URL!) as NSImage
self.Preview.image = im
})
}
@IBAction func pressAction(btnOpr: NSButton)
{
println("Hello From me")
TempLabel.stringValue = "Sending..."
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
.response { (request, response, data, error) in
println(request)
println(response)
println(error)
}
let requestSerializer = AFJSONRequestSerializer() as AFJSONRequestSerializer
let responseSerializer = AFJSONResponseSerializer() as AFJSONResponseSerializer
let tumblrCl = TMAPIClient.sharedInstance() as TMAPIClient
let jxhhtpop = JXHTTPOperation() as JXHTTPOperation
tumblrCl.OAuthConsumerKey = "sYKNnjJRqbxWWlg19sY8WYnZyQi6wURbilnE4k3vsyqX4vc4ER"
tumblrCl.OAuthConsumerSecret = "n8mtWzKieR8qgTdwUWNhF3OYZVIsvMZXvVr9DKPlCGI6wE2VLV"
tumblrCl.OAuthToken = "PyvcruFPx1YqhdAOkCWjCPWMBIYx3fUJaiFzjhxpkwUwps0VjC"
tumblrCl.OAuthTokenSecret = "Zjwmi2wYA83rtIdoL82BcWcj5sxm5QrI1MEnZX4DzFQHWydx1C"
var post_text : NSString = ""
post_text = self.weather_string + " " + BlogCaption.stringValue
let tags = "CatumblrMac ," + NSHost.currentHost().localizedName!
if (self.im_path!.path? != nil)
{
let params : [NSString : NSString]? = ["body": post_text, "caption": post_text, "tags":tags]
let fpath = self.im_path!.path! as NSString
let fext = self.im_path!.pathExtension! as NSString
let fname = self.im_path!.lastPathComponent! as NSString
tumblrCl.photo("geekhost", filePathArray: [fpath], contentTypeArray: ["image/" + fext], fileNameArray: [fname], parameters: params, callback:{ (id : AnyObject!, err : NSError!) in
if ((err?) != nil)
{
print ("Unable to post message")
}
else
{
println("Message Send")
self.TempLabel.stringValue = "Message sent!"
}
})
}
else
{
let params : [NSString : NSString]? = ["type":"text", "body": post_text, "caption": "", "tags":tags]
tumblrCl.post("geekhost", type: "text", parameters: params!, callback: { (id : AnyObject!, err : NSError!) in
if ((err?) != nil)
{
print ("Unable to post message")
}
else
{
println("Message Send")
self.TempLabel.stringValue = "Message sent!"
}
})
}
}
} |
//
// ETCCardTableViewController.swift
// Dash
//
// Created by Yuji Nakayama on 2020/01/19.
// Copyright © 2020 Yuji Nakayama. All rights reserved.
//
import UIKit
import CoreData
class ETCCardTableViewController: UITableViewController, NSFetchedResultsControllerDelegate {
enum Section: Int, CaseIterable {
case allPayments = 0
case cards
init?(_ sectionIndex: Int) {
if let section = Section(rawValue: sectionIndex) {
self = section
} else {
return nil
}
}
init?(_ indexPath: IndexPath) {
if let section = Section(rawValue: indexPath.section) {
self = section
} else {
return nil
}
}
}
var device: ETCDevice {
return Vehicle.default.etcDevice
}
lazy var deviceStatusBarItemManager = ETCDeviceStatusBarItemManager(device: device)
var fetchedResultsController: NSFetchedResultsController<ETCCardManagedObject>?
var keyValueObservations: [NSKeyValueObservation] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.contentInset.top += 12
tableView.tableFooterView = UIView()
setUpNavigationBar()
startObservingCurrentCard()
startFetchingCards()
}
func setUpNavigationBar() {
navigationItem.leftBarButtonItem = editButtonItem
deviceStatusBarItemManager.addBarItem(to: navigationItem)
}
func startObservingCurrentCard() {
keyValueObservations.append(device.observe(\.currentCard) { [weak self] (currentCard, change) in
DispatchQueue.main.async {
self?.indicateCurrentCard()
}
})
}
func startFetchingCards() {
if let managedObjectContext = device.dataStore.viewContext {
fetchCards(managedObjectContext: managedObjectContext)
} else {
keyValueObservations.append(device.dataStore.observe(\.viewContext) { [weak self] (dataStore, change) in
guard let managedObjectContext = dataStore.viewContext else { return }
self?.fetchCards(managedObjectContext: managedObjectContext)
})
}
}
func fetchCards(managedObjectContext: NSManagedObjectContext) {
fetchedResultsController = makeFetchedResultsController(managedObjectContext: managedObjectContext)
try! fetchedResultsController!.performFetch()
tableView.reloadData()
}
func makeFetchedResultsController(managedObjectContext: NSManagedObjectContext) -> NSFetchedResultsController<ETCCardManagedObject> {
let request: NSFetchRequest<ETCCardManagedObject> = ETCCardManagedObject.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
let controller = NSFetchedResultsController(
fetchRequest: request,
managedObjectContext: managedObjectContext,
sectionNameKeyPath: nil,
cacheName: nil
)
controller.delegate = self
return controller
}
func selectRowForAllPayments(animated: Bool) {
let indexPath = IndexPath(row: 0, section: Section.allPayments.rawValue)
tableView.selectRow(at: indexPath, animated: animated, scrollPosition: .none)
}
func selectRow(forCard cardUUIDString: String, animated: Bool) {
guard let cards = fetchedResultsController?.sections?.first?.objects as? [ETCCardManagedObject] else { return }
guard let row = cards.firstIndex(where: { $0.uuid.uuidString == cardUUIDString }) else { return }
let indexPath = IndexPath(row: row, section: Section.cards.rawValue)
tableView.selectRow(at: indexPath, animated: animated, scrollPosition: .none)
}
func indicateCurrentCard() {
tableView.reloadSections(IndexSet(integer: Section.cards.rawValue), with: .none)
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "show":
if let indexPath = tableView.indexPathForSelectedRow {
let paymentTableViewController = segue.destination as! ETCPaymentTableViewController
switch Section(indexPath)! {
case .allPayments:
paymentTableViewController.card = nil
case .cards:
paymentTableViewController.card = fetchedResultsController?.object(at: indexPath.adding(section: -1))
}
}
case "edit":
let navigationController = segue.destination as! UINavigationController
let cardEditViewController = navigationController.topViewController as! ETCCardEditViewController
cardEditViewController.card = (sender as! ETCCardManagedObject)
default:
break
}
}
// MARK: - UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return Section.allCases.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(section)! {
case .allPayments:
return 1
case .cards:
return fetchedResultsController?.sections?.first?.numberOfObjects ?? 0
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch Section(section)! {
case .allPayments:
return nil
case .cards:
return String(localized: "Cards")
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch Section(indexPath)! {
case .allPayments:
return tableView.dequeueReusableCell(withIdentifier: "AllPaymentsCell", for: indexPath)
case .cards:
let cell = tableView.dequeueReusableCell(withIdentifier: "ETCCardTableViewCell", for: indexPath) as! ETCCardTableViewCell
if let card = fetchedResultsController?.object(at: indexPath.adding(section: -1)) {
cell.card = card
cell.isCurrentCard = card.objectID == device.currentCard?.objectID
} else {
cell.card = nil
cell.isCurrentCard = false
}
return cell
}
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
// UITableViewCell.shouldIndentWhileEditing does not work with UITableView.Style.insetGrouped
// but this does work.
override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
guard Section(indexPath)! == .cards else { return }
guard let card = fetchedResultsController?.object(at: indexPath.adding(section: -1)) else { return }
performSegue(withIdentifier: "edit", sender: card)
}
// MARK: - NSFetchedResultsControllerDelegate
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
let sectionIndex = sectionIndex + 1
switch type {
case .insert:
tableView.insertSections(IndexSet(integer: sectionIndex), with: .left)
case .delete:
tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade)
case .move:
break
case .update:
break
@unknown default:
break
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
let indexPath = indexPath?.adding(section: 1)
let newIndexPath = newIndexPath?.adding(section: 1)
switch type {
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .left)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .fade)
case .update:
tableView.reloadRows(at: [indexPath!], with: .none)
case .move:
tableView.moveRow(at: indexPath!, to: newIndexPath!)
@unknown default:
break
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
}
|
protocol MultiSetProtocol {
associatedtype T
mutating func add(element: T)
mutating func remove(element: T)
func count(element: T) -> Int
func totalCount() -> Int
}
struct MultiSet<T: Hashable>: MultiSetProtocol {
private var dict = [T: Int]()
mutating func add(element: T) {
if contains(key: element) {
dict[element]! += 1
} else {
dict[element] = 1
}
}
mutating func remove(element: T) {
if contains(key: element) {
if dict[element] == 1 {
dict[element] = nil
return
}
dict[element]! -= 1
} else {
print("No such element")
}
}
func count(element: T) -> Int {
return dict[element] ?? 0
}
func totalCount() -> Int {
return Array(dict.values).reduce(0, +)
}
private func contains(key: T) -> Bool {
return dict[key] != nil
}
}
|
import UIKit
struct ImageName {
static let Background = "Background"
static let Ground = "Ground"
static let Water = "Water"
static let CrocMouthClosed = "CrocMouthClosed"
static let CrocMouthOpen = "CrocMouthOpen"
static let CrocMask = "CrocMask"
static let VineRoot = "VineRoot"
static let Vine = "Vine"
static let Prize = "Pineapple"
static let PrizeMask = "PineappleMask"
static let Heart = "heart-full"
static let Button = "button"
static let ButtonRestart = "button-restart"
}
struct Layer {
static let Background: CGFloat = 0
static let Crocodile: CGFloat = 1
static let Vine: CGFloat = 1
static let Prize: CGFloat = 2
static let Water: CGFloat = 3
static let UI: CGFloat = 4
}
struct PhysicsCategory {
static let Crocodile: UInt32 = 1
static let VineRoot: UInt32 = 2
static let Vine: UInt32 = 4
static let Prize: UInt32 = 8
}
struct SoundFile {
static let BackgroundMusic = "CheeZeeJungle.caf"
static let Slice = "Slice.caf"
static let Splash = "Splash.caf"
static let NomNom = "NomNom.caf"
}
struct GameConfiguration {
static let VineDataFile = ["Level-01.plist","Level-02.plist","Level-03.plist","Level-04.plist","Level-05.plist"]
static let CanCutMultipleVinesAtOnce = false
}
|
/**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:carlos@adaptive.me>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:ferran.vila.conesa@gmail.com>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Interface for Managing the Display operations
@author Carlos Lozano Diez
@since v2.0
@version 1.0
*/
public protocol IDisplay : IBaseSystem {
/**
Add a listener to start receiving display orientation change events.
@param listener Listener to add to receive orientation change events.
@since v2.0.5
*/
func addDisplayOrientationListener(listener : IDisplayOrientationListener)
/**
Returns the current orientation of the display. Please note that this may be different from the orientation
of the device. For device orientation, use the IDevice APIs.
@return The current orientation of the display.
@since v2.0.5
*/
func getOrientationCurrent() -> ICapabilitiesOrientation?
/**
Remove a listener to stop receiving display orientation change events.
@param listener Listener to remove from receiving orientation change events.
@since v2.0.5
*/
func removeDisplayOrientationListener(listener : IDisplayOrientationListener)
/**
Remove all listeners receiving display orientation events.
@since v2.0.5
*/
func removeDisplayOrientationListeners()
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
|
//
// FlatMode.swift
// ikalendar2
//
// Created by Tianwei Zhang on 4/12/21.
//
import Foundation
/// Data model for the flattened game modes.
enum FlatMode: String, Equatable, Identifiable, CaseIterable {
case regular
case gachi
case league
case salmon
var id: String { rawValue }
var name: String {
switch self {
case .regular:
return BattleMode.regular.name
case .gachi:
return BattleMode.gachi.name
case .league:
return BattleMode.league.name
case .salmon:
return GameMode.salmon.name
}
}
var shortName: String {
switch self {
case .regular:
return BattleMode.regular.shortName
case .gachi:
return BattleMode.gachi.shortName
case .league:
return BattleMode.league.shortName
case .salmon:
return GameMode.salmon.shortName
}
}
var imgFiln: String {
switch self {
case .regular:
return BattleMode.regular.imgFilnMid
case .gachi:
return BattleMode.gachi.imgFilnMid
case .league:
return BattleMode.league.imgFilnMid
case .salmon:
return "salmon"
}
}
var imgFilnLarge: String {
switch self {
case .regular:
return BattleMode.regular.imgFilnLarge
case .gachi:
return BattleMode.gachi.imgFilnLarge
case .league:
return BattleMode.league.imgFilnLarge
case .salmon:
return "grizz"
}
}
}
|
//
// TunerViewController.swift
// tune-final-project
//
// Created by Aneesh Ashutosh.
// Copyright © 2019 Aneesh Ashutosh. All rights reserved.
//
import UIKit
import WMGaugeView
import AudioKit
/*
* View controller for the tuner view.
*/
class TunerViewController: UIViewController, UIViewControllerTransitioningDelegate, TunerDelegate {
fileprivate var tuner: Tuner? // TuningFork
fileprivate var tunerView: TunerView? // Reference to the TunerView.
override func viewDidLoad() {
super.viewDidLoad()
// Set up AudioKit.
AKSettings.sampleRate = AudioKit.engine.inputNode.inputFormat(forBus: 0).sampleRate
tunerView = TunerView(frame: view.frame)
view.addSubview(tunerView!)
tuner = Tuner()
tuner?.delegate = self
tuner?.start()
}
override func viewWillDisappear(_ animated: Bool) {
tuner?.stop()
}
func tunerDidUpdate(_ tuner: Tuner, output: TunerOutput) {
// Minimum threshold to ignore
if output.amplitude < 0.01 {
tunerView?.gaugeView.value = 0.0
tunerView?.pitchLabel.text = "--"
} else {
// Display pitch
tunerView?.pitchLabel.text = output.pitch + "\(output.octave)"
tunerView?.gaugeView.value = Float(output.distance)
}
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return .default
}
}
|
//
// PathologyTests.swift
// PathologyTests
//
// Created by Kyle Truscott on 3/1/16.
// Copyright © 2016 keighl. All rights reserved.
//
import XCTest
@testable import Pathology
class PathologyTests: XCTestCase {
let testPath: CGPath = {
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 0, 0)
CGPathAddCurveToPoint(path, nil, 50, 25, 70, 10, 75, 25)
CGPathAddLineToPoint(path, nil, 50, 50)
CGPathAddQuadCurveToPoint(path, nil, 75, 150, 74, 75)
CGPathAddLineToPoint(path, nil, 0, 0)
CGPathCloseSubpath(path)
return path
}()
let testPathJSON = "[{\"pts\":[[0,0]],\"type\":\"move\"},{\"pts\":[[75,25],[50,25],[70,10]],\"type\":\"curve\"},{\"pts\":[[50,50]],\"type\":\"line\"},{\"pts\":[[74,75],[75,150]],\"type\":\"quad\"},{\"pts\":[[0,0]],\"type\":\"line\"},{\"pts\":[],\"type\":\"close\"},{\"pts\":[],\"type\":\"invalid\"}]"
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func test_Extract() {
let pathData = Pathology.extract(testPath)
XCTAssertEqual(pathData.elements[0].type, ElementType.MoveToPoint)
XCTAssertEqual(pathData.elements[0].points, [CGPointMake(0, 0)])
XCTAssertEqual(pathData.elements[1].type, ElementType.AddCurveToPoint)
XCTAssertEqual(pathData.elements[1].points, [CGPointMake(75, 25), CGPointMake(50, 25), CGPointMake(70, 10)])
XCTAssertEqual(pathData.elements[2].type, ElementType.AddLineToPoint)
XCTAssertEqual(pathData.elements[2].points, [CGPointMake(50, 50)])
XCTAssertEqual(pathData.elements[3].type, ElementType.AddQuadCurveToPoint)
XCTAssertEqual(pathData.elements[3].points, [CGPointMake(74, 75), CGPointMake(75, 150)])
XCTAssertEqual(pathData.elements[4].type, ElementType.AddLineToPoint)
XCTAssertEqual(pathData.elements[4].points, [CGPointMake(0, 0)])
XCTAssertEqual(pathData.elements[5].type, ElementType.CloseSubpath)
XCTAssertEqual(pathData.elements[5].points, [])
}
////////
func test_Path_ToArray() {
let pathData = Path(elements: [Element(type: ElementType.AddLineToPoint, points: [CGPointMake(100, 100)])])
let result = pathData.toArray()
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result[0]["type"] as? String, ElementType.AddLineToPoint.rawValue)
XCTAssertEqual((result[0]["pts"] as? [[CGFloat]])!, [[100, 100]])
}
func test_Path_ToJSON() {
let pathData = Path(
elements: [
Element(type: ElementType.AddLineToPoint, points: [CGPointMake(100, 100)])
])
do {
let result = try pathData.toJSON(NSJSONWritingOptions(rawValue: 0))
let resultString = NSString(data: result, encoding: NSUTF8StringEncoding)
let expected = "[{\"pts\":[[100,100]],\"type\":\"line\"}]"
XCTAssertEqual(resultString, expected)
} catch {
XCTFail("\(error)")
}
}
func test_Path_FromJSON() {
let JSON = testPathJSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
if let pathData = Path(JSON: JSON) {
XCTAssertEqual(pathData.elements[0].type, ElementType.MoveToPoint)
XCTAssertEqual(pathData.elements[0].points, [CGPointMake(0, 0)])
XCTAssertEqual(pathData.elements[1].type, ElementType.AddCurveToPoint)
XCTAssertEqual(pathData.elements[1].points, [CGPointMake(75, 25), CGPointMake(50, 25), CGPointMake(70, 10)])
XCTAssertEqual(pathData.elements[2].type, ElementType.AddLineToPoint)
XCTAssertEqual(pathData.elements[2].points, [CGPointMake(50, 50)])
XCTAssertEqual(pathData.elements[3].type, ElementType.AddQuadCurveToPoint)
XCTAssertEqual(pathData.elements[3].points, [CGPointMake(74, 75), CGPointMake(75, 150)])
XCTAssertEqual(pathData.elements[4].type, ElementType.AddLineToPoint)
XCTAssertEqual(pathData.elements[4].points, [CGPointMake(0, 0)])
XCTAssertEqual(pathData.elements[5].type, ElementType.CloseSubpath)
XCTAssertEqual(pathData.elements[5].points, [])
XCTAssertEqual(pathData.elements[6].type, ElementType.Invalid)
XCTAssertEqual(pathData.elements[6].points, [])
} else {
XCTFail()
}
}
func test_Path_FromJSON_Fail() {
let JSON = "CHEESE".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
if let _ = Path(JSON: JSON) {
XCTFail("Shoulda failed!")
}
}
func test_Path_FromData() {
let data = testPathJSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
do {
if let jsonArray = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [[String: AnyObject]] {
let pathData = Path(data: jsonArray)
XCTAssertEqual(pathData.elements[0].type, ElementType.MoveToPoint)
XCTAssertEqual(pathData.elements[0].points, [CGPointMake(0, 0)])
XCTAssertEqual(pathData.elements[1].type, ElementType.AddCurveToPoint)
XCTAssertEqual(pathData.elements[1].points, [CGPointMake(75, 25), CGPointMake(50, 25), CGPointMake(70, 10)])
XCTAssertEqual(pathData.elements[2].type, ElementType.AddLineToPoint)
XCTAssertEqual(pathData.elements[2].points, [CGPointMake(50, 50)])
XCTAssertEqual(pathData.elements[3].type, ElementType.AddQuadCurveToPoint)
XCTAssertEqual(pathData.elements[3].points, [CGPointMake(74, 75), CGPointMake(75, 150)])
XCTAssertEqual(pathData.elements[4].type, ElementType.AddLineToPoint)
XCTAssertEqual(pathData.elements[4].points, [CGPointMake(0, 0)])
XCTAssertEqual(pathData.elements[5].type, ElementType.CloseSubpath)
XCTAssertEqual(pathData.elements[5].points, [])
XCTAssertEqual(pathData.elements[6].type, ElementType.Invalid)
XCTAssertEqual(pathData.elements[6].points, [])
}
} catch {
XCTFail("\(error)")
}
}
func test_Path_CGPath() {
let pathData = Pathology.extract(testPath)
let builtPath = pathData.CGPath()
XCTAssert(CGPathEqualToPath(testPath, builtPath), "Build path doesn't match")
}
////////
func test_Element_ToDictionary() {
let elementData = Element(type: ElementType.AddLineToPoint, points: [CGPointMake(100, 100)])
let result = elementData.toDictionary()
XCTAssertEqual(result["type"] as? String, ElementType.AddLineToPoint.rawValue)
XCTAssertEqual((result["pts"] as? [[CGFloat]])!, [[100, 100]])
}
func test_Element_ToJSON() {
let elementData = Element(type: .AddLineToPoint, points: [CGPointMake(100, 100)])
do {
let result = try elementData.toJSON(NSJSONWritingOptions(rawValue: 0))
let resultString = NSString(data: result, encoding: NSUTF8StringEncoding)
let expected = "{\"pts\":[[100,100]],\"type\":\"line\"}"
XCTAssertEqual(resultString, expected)
} catch {
XCTFail("\(error)")
}
}
func test_thing() {
}
}
|
//
// EventTableViewCell.swift
// StudyBuddy
//
// Created by Vikram Idury on 10/31/17.
// Copyright © 2017 Alexander You. All rights reserved.
//
import UIKit
import FirebaseDatabase
import FirebaseAuth
import FirebaseStorage
import MapKit
class EventTableViewCell: UITableViewCell {
@IBOutlet weak var eventLabel: UILabel!
var eventId: String!
var event: Event!
var ref: DatabaseReference!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func refreshLabels () {
ref = Database.database().reference()
ref.child("events").child(self.eventId).observe(.value, with: { snapshot in
if snapshot.exists() {
let mapping = snapshot.value as! [String:String]
let name = mapping["name"]
let time = mapping["time"]
let location = mapping["location"]
//let location = CLLocation(latitude: 30.2672, longitude: -97.7431)
self.event = Event(eid: self.eventId, name: name!, time: time!, location: location!, latitude:"-97.7431", longitude:"30.2672")
self.eventLabel.text = self.event.name
}
})
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
import Domain
import Foundation
final class Repository {
let id: Int64
let name: String
let fullName: String?
let owner: User?
let url: URL
let forksCount: Int?
let openIssuesCount: Int?
let watchersCount: Int?
let stargazersCount: Int?
let language: String?
let updatedAt: Date?
let `private`: Bool?
let description: String?
init(with repo: Domain.Repository) {
id = repo.id
name = repo.name
fullName = repo.fullName
if let owner = repo.owner {
self.owner = User(with: owner)
} else {
owner = nil
}
url = repo.url
forksCount = repo.forksCount
openIssuesCount = repo.openIssuesCount
watchersCount = repo.watchersCount
stargazersCount = repo.stargazersCount
language = repo.language
updatedAt = repo.updatedAt
`private` = repo.private
description = repo.description
}
}
|
//
// ViewController.swift
// TempusFugit
//
// Created by Jasmee Sengupta on 21/03/18.
// Copyright © 2018 Jasmee Sengupta. All rights reserved.
// next: create a timer app
//separate this timeout sign out app
import UIKit
var count = 0
var testTimeOut = 10.0
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
AppTimer.startTimer(period: testTimeOut)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class CustomWindow: UIWindow {
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
print("touched now \(count)")
count += 1
AppTimer.resetTimer()
return false
}
}
class AppTimer {
//private static var timeout = 10//20 * 60 * 60
//private static var timeRemaining = timeout
private static var appTimer: Timer?
static func startTimer(period: Double) {
//appTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
appTimer = Timer.scheduledTimer(timeInterval: period, target: self, selector: #selector(endTimer), userInfo: nil, repeats: false)
}
// @objc private static func updateTimer() {
// if timeRemaining > 0 {
// timeRemaining -= 1
// } else if timeRemaining == 0 {
// endTimer()
// }
// }
@objc private static func endTimer() {
if let _ = appTimer {
appTimer!.invalidate()
print("20 minutes expired, you will be signed out")
// SIGNOUT //notification?
}
}
static func resetTimer() {
//print("\(timeRemaining) of \(timeout)")
if let _ = appTimer {
appTimer!.invalidate()
}
//timeRemaining = timeout
print("Timer reset")
AppTimer.startTimer(period: testTimeOut)
}
}
|
//
// PokemonManager.swift
// Pokemon-Index
//
// Created by Mikołaj Szadkowski on 06/05/2020.
// Copyright © 2020 Mikołaj Szadkowski. All rights reserved.
//
import UIKit
import CoreData
protocol PokemonRequestDelegate {
func pokemonRequestDidFinish()
func pokemonRequestDidFinishWithError()
}
struct PokemonManager {
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var pokemonArray: [Pokemon]?
var pokemonChosen: Pokemon?
var baseString = "https://pokeapi.co/api/v2/"
var delegate: PokemonRequestDelegate?
// Get API info about Pokemon
func requestPokemon(pokemonName: String) {
let urlString = String("\(baseString)/pokemon/\(pokemonName)/")
if let url = URL(string: urlString) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error?.localizedDescription ?? "There was unknown error in requestPokemon\task")
} else {
if let safeData = data {
let pokemonData = self.parsePokemonJSON(newData: safeData)
self.saveItems()
if pokemonData == nil {
self.delegate?.pokemonRequestDidFinishWithError()
} else {
self.delegate?.pokemonRequestDidFinish()
}
}
}
}
task.resume()
}
}
// Decode JSON file into Pokemon Object
func parsePokemonJSON(newData: Data) -> Pokemon? {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(PokemonData.self, from: newData)
let pokemon = Pokemon(context: self.context)
pokemon.id = String(decodedData.order)
pokemon.name = decodedData.name.capitalized
pokemon.image_url = decodedData.sprites.front_default
pokemon.image_front = getPokemonImage(url: decodedData.sprites.front_default)
let pokemonStats = adjustPokemonStats(data: decodedData)
pokemon.attack = pokemonStats["attack"]
pokemon.defense = pokemonStats["defense"]
pokemon.hp = pokemonStats["hp"]
pokemon.speed = pokemonStats["speed"]
pokemon.special_attack = pokemonStats["special-attack"]
pokemon.special_defense = pokemonStats["special-defense"]
pokemon.type1 = decodedData.types[0].type.name
if decodedData.types.count == 2 {
pokemon.type2 = decodedData.types[1].type.name
}
return pokemon
} catch {
print(error.localizedDescription)
return nil
}
}
// Download image sprite for pokemon
func getPokemonImage(url: String) -> Data? {
if let url = URL(string: url) {
do {
let imageData = try Data(contentsOf: url, options: [])
let image = UIImage(data: imageData)
return image?.jpegData(compressionQuality: 1.0)
}
catch {
print(error.localizedDescription)
}
}
return nil
}
// Adjust Stats for pokemons
func adjustPokemonStats(data: PokemonData) -> [String : String] {
var pokemonStats = [String : String]()
for number in 0...data.stats.count - 1 {
pokemonStats[data.stats[number].stat.name] = String(data.stats[number].base_stat)
}
return pokemonStats
}
// Save Pokemon to Core Data
func saveItems() {
do {
try self.context.save()
} catch {
print(error.localizedDescription)
}
}
// Load Pokemons to pokemonArray
mutating func loadItems(with request: NSFetchRequest<Pokemon> = Pokemon.fetchRequest()) {
do {
pokemonArray = try context.fetch(request)
} catch {
print("Error while fetching Item data: \(error.localizedDescription)")
}
}
// Delete Pokemon
func deletePokemon(pokemon: NSManagedObject) {
context.delete(pokemon)
do {
try context.save()
print("Pokemon deleted")
} catch {
print(error.localizedDescription)
}
}
}
|
//
// RootTabBarNavigator.swift
// CaptainDemo
//
// Created by Vincent Esche on 6/6/18.
// Copyright © 2018 Vincent Esche. All rights reserved.
//
import UIKit
import Captain
class RootTabBarNavigator {
var _source: Source
var presentingNavigator: AnyNavigator?
required init(source: Source) {
self._source = source
}
}
extension RootTabBarNavigator: AnyNavigator {
func dismissAny(from source: AnyNavigationSource) throws {
fatalError()
}
}
extension RootTabBarNavigator: Navigator {
typealias Source = RootTabBarController
typealias Route = RootTabBarRoute
func prepare(navigation: Navigation<Route, Source, Navigator.Destination>) throws {
switch navigation.route {
case .continents(_):
guard let destination = navigation.destination as? ContinentsTableViewController else {
return
}
destination.managedObjectContext = navigation.source.managedObjectContext
case .oceans(_):
guard let destination = navigation.destination as? OceansTableViewController else {
return
}
destination.managedObjectContext = navigation.source.managedObjectContext
}
}
func navigate(from source: Source, to route: Route) throws {
let selectedIndex: Int
switch route {
case .continents(_):
selectedIndex = 0
case .oceans(_):
selectedIndex = 1
}
source.selectedIndex = selectedIndex
let builder = try self.anyBuilder(for: route, from: source)
let destinations = try builder.destinations(for: route, from: source, on: self)
let strategy = try self.anyStrategy(for: route, from: source)
try strategy.present(destinations, from: source)
}
func nextDestination(
for route: Route,
from source: Source
) throws -> AnyNavigationDestination {
switch route {
case .continents(_):
let storyboard = UIStoryboard(name: "Continents", bundle: nil)
return storyboard.instantiateInitialViewController()!
case .oceans(_):
let storyboard = UIStoryboard(name: "Oceans", bundle: nil)
return storyboard.instantiateInitialViewController()!
}
}
public func builder(
for route: Route,
from source: Source
) throws -> NavigationBuilder {
return DeepNavigationBuilder()
}
public func strategy(
for route: Route,
from source: Source
) throws -> PresentationStrategy {
return TabBarPresentationStrategy()
}
}
extension RootTabBarNavigator: GlobalNavigator {
typealias RootNavigator = RootTabBarNavigator
var rootNavigator: RootNavigator {
return self
}
func navigate(to route: RootNavigator.Route) throws {
try self.navigate(
from: self.source,
to: route
)
}
}
extension RootTabBarNavigator: RootNavigator {
var source: Source {
return self._source
}
}
|
//
// RestaurantContentView.swift
// caffinho-iOS
//
// Created by Rodolfo Mantovani on 6/10/16.
// Copyright © 2016 venturus. All rights reserved.
//
import Foundation
import UIKit
public class RestaurantContentView: UIView{
@IBOutlet weak var continueButton: UIButton!
@IBOutlet weak var restaurantPicker: UIPickerView!
} |
//
// EtcInject.swift
// DHBC
//
// Created by Kiều anh Đào on 7/3/20.
// Copyright © 2020 Anhdk. All rights reserved.
//
import Swinject
import RxSwift
import EventKit
final class EtcInject {
static let shared = EtcInject()
let container = Container()
private init() {
container.register(DisposeBag.self) { _ in
DisposeBag()
}
container.register(Date.self) { _ in
Date()
}
container.register(EKEventStore.self) { _ in
EKEventStore()
}
}
}
|
//
// TimelineRefreshCell.swift
// J.YoutubeWatcher
//
// Created by JinYoung Lee on 24/04/2019.
// Copyright © 2019 JinYoung Lee. All rights reserved.
//
import Foundation
import UIKit
class TimelineRefreshCell: UITableViewCell {
@IBOutlet weak var activityController: UIActivityIndicatorView!
override func awakeFromNib() {
activityController.startAnimating()
}
func startAnimate() {
activityController.startAnimating()
}
}
|
//
// RDGliderViewController.swift
// GliderSample
//
// Created by Guillermo Delgado on 25/04/2017.
// Copyright © 2017 Guillermo Delgado. All rights reserved.
//
import UIKit
@objc public protocol RDGliderViewControllerDelegate: class {
/**
Delegate method to notify invoke object when offset has changed
*/
func glideViewController(glideViewController: RDGliderViewController, hasChangedOffsetOfContent offset: CGPoint)
/**
Delegate method to notify invoke object when glideView will increase offset by one
*/
func glideViewControllerWillExpand(glideViewController: RDGliderViewController)
/**
Delegate method to notify invoke object when glideView will decrease offset by one
*/
func glideViewControllerWillCollapse(glideViewController: RDGliderViewController)
/**
Delegate method to notify invoke object when glideView did increase offset by one
*/
func glideViewControllerDidExpand(glideViewController: RDGliderViewController)
/**
Delegate method to notify invoke object when glideView did decrease offset by one
*/
func glideViewControllerDidCollapse(glideViewController: RDGliderViewController)
}
@objc public class RDGliderViewController: UIViewController, UIScrollViewDelegate {
public weak var delegate: RDGliderViewControllerDelegate?
var scrollView: RDScrollView?
/**
Content view Controller hosted on the scrollView
*/
public private(set) var contentViewController: UIViewController?
/**
Margin of elastic animation default is 20px
*/
public var marginOffset: Float {
get {
return self.scrollView != nil ? self.scrollView!.margin: 0.0
}
set {
self.scrollView?.margin = newValue
}
}
/**
Sorted list of offsets in % of contentVC view. from 0 to 1
*/
public var offsets: [NSNumber] {
get {
if self.scrollView == nil {
NSException(name:NSExceptionName(rawValue: "Internal Inconsistency"),
reason:"RDGliderViewController have to instantiate first on a viewController").raise()
}
return (self.scrollView?.offsets)!
}
set {
if newValue.count > 0 {
if self.scrollView == nil {
NSException(name:NSExceptionName(rawValue: "Internal Inconsistency"),
reason:"RDGliderViewController have to instantiate first on a viewController").raise()
}
self.scrollView?.offsets = newValue
} else {
NSException(name:NSExceptionName(rawValue: "Invalid offsets"),
reason:"Array of offsets cannot be Zero").raise()
}
}
}
/**
Orientation type of the glide view
*/
public private(set) var orientationType: RDScrollViewOrientationType {
get {
if self.scrollView == nil {
return .RDScrollViewOrientationUnknown
}
return self.scrollView!.orientationType
}
set { }
}
/**
Current offset of the glide view
*/
public private(set) var currentOffsetIndex: Int {
get {
if self.scrollView == nil {
return 0
}
return self.scrollView!.offsetIndex
}
set { }
}
/**
Returns a bool for determining if the glide view isn't closed, is different than offset % 0.
*/
public private(set) var isOpen: Bool {
get {
if self.scrollView == nil {
return false
}
return self.scrollView!.isOpen
}
set { }
}
/**
Bool meant for enabling the posibility to close the glide view dragging, Default value is NO
*/
public var disableDraggingToClose: Bool = false
/**
Initializator of the object, it requires the parent view controller to build its components
* @param parent Parent Class of this instance
* @param content external ViewController placed as a content of the GlideView
* @param type of GlideView Left to Right, Right to Left, Bottom To Top and Top to Bottom.
* @param offsets Array of offsets in % (0 to 1) dependent of Content size if not expecified UIScreen bounds.
* @return A newly created RDGliderViewController instance
*/
public init(parent: UIViewController, WithContent content: RDGliderContentViewController,
AndType type: RDScrollViewOrientationType, WithOffsets offsets: [NSNumber]) {
super.init(nibName: nil, bundle: nil)
parent.addChildViewController(self)
self.scrollView = RDScrollView.init(frame: CGRect.init(x:0, y:0, width:parent.view.frame.width,
height:parent.view.frame.height))
parent.view.addSubview(self.scrollView!)
self.setContentViewController(Content: content, AndType: type, WithOffsets: offsets)
}
/**
Init Disabled
*/
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
Change contentViewController type and offsets after the VC has been initialized.
* @param content external ViewController placed as a content of the GlideView
* @param type of GlideView Left to Right, Right to Left, Bottom To Top and Top to Bottom.
* @param offsets Array of offsets in % (0 to 1) dependent of Content size if not expecified UIScreen */
public func setContentViewController(Content content: RDGliderContentViewController,
AndType type: RDScrollViewOrientationType, WithOffsets offsets: [NSNumber]) {
let checkContent: RDGliderContentViewController? = content
if checkContent == nil {
NSException(name:NSExceptionName(rawValue: "Invalid RDGliderContentViewController value"),
reason:"RDGliderContentViewController cannot be nil").raise()
}
self.parent?.automaticallyAdjustsScrollViewInsets = false
self.automaticallyAdjustsScrollViewInsets = false
self.scrollView?.orientationType = type
self.scrollView?.offsets = offsets
self.contentViewController = content
self.scrollView?.content = (self.contentViewController?.view)!
self.scrollView?.delegate = self
self.close()
}
/**
Increase the position of the Gliver view by one in the list of offsets
*/
public func expand() {
self.delegate?.glideViewControllerWillExpand(glideViewController: self)
self.scrollView?.expandWithCompletion(completion: { (_) in
self.delegate?.glideViewControllerDidExpand(glideViewController: self)
})
}
/**
Decrease the position of the Gliver view by one in the list of offsets
*/
public func collapse() {
self.delegate?.glideViewControllerWillCollapse(glideViewController: self)
self.scrollView?.collapseWithCompletion(completion: { (_) in
self.delegate?.glideViewControllerDidCollapse(glideViewController: self)
})
}
/**
This method moves the View directly to the first offset which is the default position.
*/
public func close() {
self.delegate?.glideViewControllerWillCollapse(glideViewController: self)
self.scrollView?.closeWithCompletion(completion: { (_) in
self.delegate?.glideViewControllerDidCollapse(glideViewController: self)
})
}
/**
This method gives a shake to the Gliver view, is meant to grap users atention.
*/
public func shake() {
if self.scrollView == nil {
return
}
let shakeMargin: CGFloat = 10.0
let animation: CABasicAnimation = CABasicAnimation.init(keyPath: "position")
animation.duration = 0.05
animation.repeatCount = 2
animation.autoreverses = true
animation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut)
if self.orientationType == .RDScrollViewOrientationRightToLeft {
animation.fromValue = NSValue.init(cgPoint: self.scrollView!.center)
animation.toValue = NSValue.init(cgPoint: CGPoint.init(x: self.scrollView!.center.x + shakeMargin,
y: self.scrollView!.center.y))
} else if self.orientationType == .RDScrollViewOrientationLeftToRight {
animation.fromValue = NSValue.init(cgPoint: self.scrollView!.center)
animation.toValue = NSValue.init(cgPoint: CGPoint.init(x: self.scrollView!.center.x - shakeMargin,
y: self.scrollView!.center.y))
} else if self.orientationType == .RDScrollViewOrientationBottomToTop {
animation.fromValue = NSValue.init(cgPoint: self.scrollView!.center)
animation.toValue = NSValue.init(cgPoint: CGPoint.init(x: self.scrollView!.center.x,
y: self.scrollView!.center.y + shakeMargin))
} else if self.orientationType == .RDScrollViewOrientationTopToBottom {
animation.fromValue = NSValue.init(cgPoint: self.scrollView!.center)
animation.toValue = NSValue.init(cgPoint: CGPoint.init(x: self.scrollView!.center.x,
y: self.scrollView!.center.y - shakeMargin))
}
self.scrollView?.layer.add(animation, forKey: "position")
}
/**
Change offset of view.
* @param offsetIndex setNew Offset of GlideView, parameter needs to be within offsets Array count list.
* @param animated animates the offset change
*/
public func changeOffset(to offsetIndex: Int, animated: Bool) {
if self.currentOffsetIndex < offsetIndex {
self.delegate?.glideViewControllerWillExpand(glideViewController: self)
} else if offsetIndex < self.currentOffsetIndex {
self.delegate?.glideViewControllerWillCollapse(glideViewController: self)
}
self.scrollView?.changeOffsetTo(offsetIndex: offsetIndex, animated: animated, completion: { (_) in
if self.currentOffsetIndex < offsetIndex {
self.delegate?.glideViewControllerDidExpand(glideViewController: self)
} else {
self.delegate?.glideViewControllerDidCollapse(glideViewController: self)
}
})
}
// MARK: - UIScrollViewDelegate
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.delegate?.glideViewController(glideViewController: self,
hasChangedOffsetOfContent: scrollView.contentOffset)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.changeOffset(to: self.nearestOffsetIndex(to: scrollView.contentOffset), animated:false)
}
public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
scrollView.setContentOffset(scrollView.contentOffset, animated: false)
}
// MARK: - private Methods
internal func nearestOffsetIndex(to contentOffset: CGPoint) -> Int {
var index: Int = 0
var offset: CGFloat = contentOffset.x
var threshold: CGFloat = self.scrollView!.content!.frame.width
if self.orientationType == .RDScrollViewOrientationBottomToTop ||
self.orientationType == .RDScrollViewOrientationTopToBottom {
offset = contentOffset.y
threshold = self.scrollView!.content!.frame.height
}
var distance: CGFloat = CGFloat.greatestFiniteMagnitude
for i in 0..<self.offsets.count {
let transformedOffset: CGFloat = CGFloat(self.scrollView!.offsets[i].floatValue) * threshold
let distToAnchor: CGFloat = fabs(offset - transformedOffset)
if distToAnchor < distance {
distance = distToAnchor
index = i
}
}
return (index == 0 && self.disableDraggingToClose) ? 1: index
}
// MARK: - Rotation event
public override func viewWillTransition(to size: CGSize,
with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if self.contentViewController != nil {
self.contentViewController!.viewWillTransition(to: size, with: coordinator)
}
coordinator.animate(alongsideTransition: { _ in
self.changeOffset(to: self.currentOffsetIndex, animated: true)
}) { _ in
self.scrollView!.recalculateContentSize()
}
}
}
|
//
// ViewController.swift
// Target13-Machine
//
// Created by Air_chen on 2016/11/7.
// Copyright © 2016年 Air_chen. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var picker:UIPickerView!
@IBOutlet weak var beginBtn:UIButton!
@IBOutlet weak var lab:UILabel!
var imageArray = [String]()
var dataArray1 = [Int]()
var dataArray2 = [Int]()
var dataArray3 = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
imageArray = ["👻","👸","💩","😘","🍔","🤖","🍟","🐼","🚖","🐷"]
for _ in 0...99 {
dataArray1.append((Int)(arc4random() % 10 ))
dataArray2.append((Int)(arc4random() % 10 ))
dataArray3.append((Int)(arc4random() % 10 ))
}
lab.text = ""
picker.delegate = self
picker.dataSource = self
beginBtn.addTarget(self, action: #selector(ViewController.touchBeginAction), for: UIControlEvents.touchUpInside)
}
func touchBeginAction() {
picker.selectRow((Int)(arc4random() % 10 ), inComponent: 0, animated: true)
picker.selectRow((Int)(arc4random() % 10 ), inComponent: 1, animated: true)
picker.selectRow((Int)(arc4random() % 10 ), inComponent: 2, animated: true)
if (dataArray1[picker.selectedRow(inComponent: 0)] == dataArray2[picker.selectedRow(inComponent: 1)]) && (dataArray2[picker.selectedRow(inComponent: 1)] == dataArray3[picker.selectedRow(inComponent: 2)]) {
lab.text = "Bingo!!"
}else{
lab.text = "💔"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UIPickerViewDataSource, UIPickerViewDelegate{
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 100
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return 100.0
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 100.0
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let pickerLab = UILabel()
if component == 0{
pickerLab.text = imageArray[Int(dataArray1[row])]
}else if component == 1{
pickerLab.text = imageArray[Int(dataArray2[row])]
}else{
pickerLab.text = imageArray[Int(dataArray3[row])]
}
pickerLab.font = UIFont(name: "Apple Color Emoji", size: 80)
pickerLab.textAlignment = NSTextAlignment.center
return pickerLab
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.