text stringlengths 8 1.32M |
|---|
//
// FirstViewController.swift
// mojo_test
//
// Created by Yunyun Chen on 11/28/18.
// Copyright © 2018 Yunyun Chen. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController {
//MARK: properties
@IBOutlet weak var profileImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
profileImage.isUserInteractionEnabled = true
let swiftUp = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeGesture))
swiftUp.direction = UISwipeGestureRecognizer.Direction.up
profileImage.addGestureRecognizer(swiftUp)
}
//MARK: actions
@objc func swipeGesture(sendr:UISwipeGestureRecognizer) {
if let swipeGesture = sendr as? UISwipeGestureRecognizer
{
switch swipeGesture.direction {
case UISwipeGestureRecognizer.Direction.up:
print("Swipe Up")
profileImage.image = UIImage(named:"2")
default:
break
}
}
}
}
|
//
// Card.swift
// DeckOfOneCard
//
// Created by Austin Blaser on 8/29/16.
// Copyright © 2016 Austin Blaser. All rights reserved.
//
import Foundation
class Card {
private let kSuit = "suit"
private let kValue = "value"
private let kImageString = "image"
let suit : String
let value: String
let imageString: String
init?(dictionary: [String: AnyObject]){
guard let suit = dictionary[kSuit] as? String,
value = dictionary[kValue] as? String,
imageString = dictionary[kImageString] as? String else {return nil}
self.suit = suit
self.value = value
self.imageString = imageString
}
}
|
//
// CustomViews.swift
// DUMessagingUIKit
//
// Created by Pofat Diuit on 2016/6/3.
// Copyright © 2016年 duolC. All rights reserved.
//
import Foundation
import UIKit
/// This is a customized UILabel where their text alway align in top vertically
@IBDesignable open class TopAlignedLabel: UILabel {
override open func drawText(in rect: CGRect) {
if let stringText = text {
let stringTextAsNSString = stringText as NSString
let labelStringSize = stringTextAsNSString.boundingRect(with: CGSize(width: self.frame.width, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil).size
super.drawText(in: CGRect(x: 0, y: 0, width: self.frame.width, height: ceil(labelStringSize.height)))
} else {
super.drawText(in: rect)
}
}
override open func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
layer.borderWidth = 1
layer.borderColor = UIColor.black.cgColor
}
}
@IBDesignable open class DUAvatarImageView: UIImageView, CircleShapeView, DUImageResource {
// Automatically load the image right after its url is set
open var imagePath: String? = "" {
didSet {
if self.imagePath != "" {
self.loadImage() { [weak self] in
self?.image = self?.imageValue
}
}
}
}
}
open class RoundUIView: UIView, CircleShapeView { }
|
//
// SideMenuOptionController.swift
// SideMenuHUB
//
// Created by Daniel Yo on 12/17/17.
// Copyright © 2017 Daniel Yo. All rights reserved.
//
import UIKit
import IGListKit
//MARK: Protocols
protocol SideMenuOptionSectionControllerDelegate {
func didSelectSideMenuOptionItem(item:ModuleOption)
}
class SideMenuOptionController: ListSectionController {
var delegate:SideMenuOptionSectionControllerDelegate?
var revealWidth:CGFloat?
var optionArray:Array = [ModuleOption]()
//MARK: ListSectionController
override func numberOfItems() -> Int {
return self.optionArray.count
}
override func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: self.collectionContext!.containerSize.width, height: 55)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
let cell:SideMenuOptionCollectionViewCell = self.collectionContext!.dequeueReusableCell(of: SideMenuOptionCollectionViewCell.self, for: self, at: index) as! SideMenuOptionCollectionViewCell
cell.name = self.optionArray[index].name
cell.image = self.optionArray[index].image
cell.updateWithRevealWidth(revealWidth: self.revealWidth!)
return cell
}
override func didUpdate(to object: Any) {
let diffableArray:ListDiffableArray = object as! ListDiffableArray
self.optionArray = diffableArray.array! as! Array<ModuleOption>
}
override func didSelectItem(at index: Int) {
//if delegate exists and conforms to method
if let delegateVC = self.delegate {
delegateVC.didSelectSideMenuOptionItem(item: self.optionArray[index])
}
}
}
|
//
// TimelapseCell.swift
// Sagas.Life
//
// Created by Sergey Koval on 12/8/19.
// Copyright © 2019 Pharos Production Inc. All rights reserved.
//
import UIKit
class SagaCell: UITableViewCell {
@IBOutlet weak var photoView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var tagsLabel: UILabel!
@IBOutlet weak var photosLabel: UILabel!
@IBOutlet weak var likesLabel: UILabel!
@IBOutlet weak var commentsLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
photoView.layer.masksToBounds = true
backgroundColor = .clear
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// HolidayGather.swift
// Schedule_B
//
// Created by KEEN on 2021/02/23.
//
import Foundation
struct HolidayGather {
private let apiKey = "9c57014c99e72d106d1fe7b23487390294256eb5"
private let urlEndpoint = "https://calendarific.com/api/v2/holidays?"
/**
Get national holidays from external api server [Calendarific](https://calendarific.com)
- parameter country: National Holiday to retrieve (US or Korea)
- parameter handler: Function handle data come from api sever ( work asynchronously)
*/
struct Holiday: Codable {
let dateInt: Int
let title: String
let description: String
let type: HolidayType
enum HolidayType: String, Codable {
case national = "National holiday"
case observance = "Observance"
case season = "Season"
case commonLocal = "Common local holiday"
}
init(from data: Response.HolidayCapsule){
self.dateInt = (data.date.datetime["year"]! * 10000) + (data.date.datetime["month"]! * 100) + data.date.datetime["day"]!
self.title = data.name
self.description = data.description
self.type = HolidayType(rawValue: data.type[0]) ?? .national
}
}
enum CountryCode: String{
case korea = "KR"
case america = "US"
}
func retrieveHolidays(about year: Int, of country: CountryCode, handler: @escaping (Data) -> Void) {
let urlString = urlEndpoint + "&api_key=" + apiKey + "&country=" + country.rawValue + "&year=" + String(year)
let url = URL(string: urlString)!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else {
print("Fail to get holiday data from server")
print("response: \(response.debugDescription)")
print("error: \(error.debugDescription)")
return }
handler(data)
}
task.resume()
}
struct Response: Codable {
var meta: [String: Int]
var response: Data
struct Data: Codable {
var holidays: [HolidayCapsule]
}
struct HolidayCapsule: Codable {
var name: String
var type: [String]
var description: String
var date: DateCapsule
struct DateCapsule: Codable {
var iso: String
var datetime: [String: Int]
}
}
}
}
|
class MyQueue {
private var stack = [Int]()
private var temp = [Int]()
private func shift() {
while !stack.isEmpty {
temp.append(stack.popLast()!)
}
}
func push(_ x: Int) {
stack.append(x)
}
func pop() -> Int {
guard temp.isEmpty else { return temp.popLast()! }
shift()
return temp.popLast()!
}
func peek() -> Int {
guard temp.isEmpty else { return temp.last! }
shift()
return temp.last!
}
func empty() -> Bool {
return stack.isEmpty && temp.isEmpty
}
} |
//
// WebService.swift
// ShowsApp
//
// Created by MARCOS ALESSANDRO FONSECA on 6/18/15.
// Copyright (c) 2015 MARCOS ALESSANDRO FONSECA. All rights reserved.
//
import Foundation
@objc class WebService: NSObject
{
class func loadMovies(urlAddress:String, completionHandler: (result:String!, errorCode:Int) ->())
{
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: urlAddress)
request.HTTPMethod = "GET"
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if (error != nil)
{
completionHandler(result: Utils.getErrorMessageByCode(error.code), errorCode: error.code)
}
else
{
var strData:String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
completionHandler(result: strData, errorCode: 0)
}
})
}
} |
// RUN: %target-swift-frontend %s -parse -verify
// REQUIRES: objc_interop
import Foundation
func useUnavailable() {
var a = NSSimpleCString() // expected-error {{'NSSimpleCString' is unavailable}}
var b = NSConstantString() // expected-error {{'NSConstantString' is unavailable}}
}
func encode(_ string: String) {
_ = string.cString(using: NSUTF8StringEncoding) // expected-error {{'NSUTF8StringEncoding' has been renamed to 'String.Encoding.utf8'}} {{29-49=String.Encoding.utf8}}
let _: NSStringEncoding? = nil // expected-error {{'NSStringEncoding' has been renamed to 'String.Encoding'}} {{10-26=String.Encoding}}
} |
//
// ZGUILabelExtension.swift
// Pods
//
// Created by zhaogang on 2017/5/13.
//
//
import UIKit
import Foundation
import UIKit
import ZGCore
public extension UILabel {
/// 采用html标签方式设置样式
///
/// - parameter styleText: 取值如:`<font face='Helvetica' size='13' color='#E50F3C' line='u' >Hello world</font>`
///
public func htmlStyleText(_ styleText:String?) {
guard let htmlText = styleText else {
return
}
self.attributedText = ZGUILabelStyle.attributedStringOfHtmlText(htmlText)
}
public func differentFontAndColor(lable : UILabel, differentText : String, differentTextColor : UIColor? = nil,differentTextFont : UIFont? = nil) {
guard let text = lable.text else{
return
}
guard let differentTextColor = differentTextColor else {
return
}
let attrstring:NSMutableAttributedString = NSMutableAttributedString(string:text)
let str = NSString(string: text)
let theRange = str.range(of: differentText)
if differentTextColor != nil {
attrstring.addAttribute(NSAttributedString.Key.foregroundColor, value: differentTextColor, range: theRange)
}else{
attrstring.addAttribute(NSAttributedString.Key.foregroundColor, value: lable.textColor, range: theRange)
}
if differentTextFont != nil {
attrstring.addAttribute(NSAttributedString.Key.font, value: differentTextFont, range: theRange)
}else{
attrstring.addAttribute(NSAttributedString.Key.font, value: lable.font, range: theRange)
}
lable.attributedText = attrstring
}
}
|
//
// RecordItem.swift
// SPHTechApp
//
// Created by Hoang Nguyen on 6/5/20.
// Copyright © 2020 Hoang Nguyen. All rights reserved.
//
import Foundation
struct RecordItem: Equatable {
let id: Int
let volumeOfMobileData: Float
let quater: String
}
|
//
// MyContactsTests.swift
// MyContactsTests
//
// Created by Karthik on 09/06/18.
// Copyright © 2018 company. All rights reserved.
//
import XCTest
@testable import MyContacts
class MyContactsTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testFetchContacts() {
let expectation = XCTestExpectation(description: "Fetch Contacts")
let url = URL(string: Constants.BaseURL+Constants.GetContacts)!
let dataTask = URLSession.shared.dataTask(with: url) { (data, _, _) in
XCTAssertNotNil(data, "No data")
expectation.fulfill()
}
dataTask.resume()
wait(for: [expectation], timeout: 10.0)
}
}
|
//
// String.swift
// Marvel
//
// Created by MACBOOK on 21/05/2021.
//
import Foundation
extension String {
var isBlank: Bool {
let trimmed = trimmingCharacters(in: .whitespaces)
return trimmed.isEmpty
}
var nilIfEmpty: String? {
isBlank ? nil : self
}
}
|
//
// Renderer.swift
// Satin
//
// Created by Reza Ali on 7/23/19.
// Copyright © 2019 Reza Ali. All rights reserved.
//
import Metal
import simd
open class Renderer
{
public var preDraw: ((_ renderEncoder: MTLParallelRenderCommandEncoder) -> ())?
public var postDraw: ((_ renderEncoder: MTLParallelRenderCommandEncoder) -> ())?
public var scene: Object = Object()
public var camera: Camera = Camera()
public var context: Context?
{
didSet
{
if let context = self.context
{
scene.context = context
}
updateColorTexture = true
updateDepthTexture = true
updateStencilTexture = true
updateShadowTexture = true
updateShadowMaterial = true
}
}
public var size: (width: Float, height: Float) = (0, 0)
{
didSet
{
let width = Double(size.width)
let height = Double(size.height)
viewport = MTLViewport(originX: 0.0, originY: 0.0, width: width, height: height, znear: 0.0, zfar: 1.0)
updateColorTexture = true
updateDepthTexture = true
updateStencilTexture = true
updateShadowTexture = true
}
}
var lightViewMatrix: matrix_float4x4 = matrix_identity_float4x4
var lightProjectionMatrix: matrix_float4x4 = matrix_identity_float4x4
var light = Object()
public var lightPosition: simd_float3 = simd_make_float3(0.0, 10.0, 0.0)
{
didSet
{
setupLight()
}
}
public var lightDirection: simd_float3 = simd_make_float3(0.0, -1.0, 0.0)
{
didSet
{
setupLight()
}
}
var shadowMatrix: matrix_float4x4 = matrix_identity_float4x4
var updateShadowMaterial = true
var shadowMaterial: ShadowMaterial?
public var enableShadows: Bool = true
var updateShadowTexture: Bool = true
var shadowTexture: MTLTexture?
var shadowPipelineState: MTLRenderPipelineState?
let shadowRenderPassDescriptor = MTLRenderPassDescriptor()
var uniformBufferIndex: Int = 0
var uniformBufferOffset: Int = 0
var shadowUniforms: UnsafeMutablePointer<ShadowUniforms>!
var shadowUniformsBuffer: MTLBuffer!
public var autoClearColor: Bool = true
public var clearColor: MTLClearColor = MTLClearColorMake(0.0, 0.0, 0.0, 1.0)
public var updateColorTexture: Bool = true
public var colorTexture: MTLTexture?
public var updateDepthTexture: Bool = true
public var depthTexture: MTLTexture?
public var depthLoadAction: MTLLoadAction = .clear
public var depthStoreAction: MTLStoreAction = .dontCare
public var clearDepth: Double = 1.0
public var updateStencilTexture: Bool = true
public var stencilTexture: MTLTexture?
public var stencilLoadAction: MTLLoadAction = .clear
public var stencilStoreAction: MTLStoreAction = .dontCare
public var clearStencil: UInt32 = 0
public var viewport: MTLViewport = MTLViewport()
public init(context: Context,
scene: Object,
camera: Camera)
{
self.scene = scene
self.camera = camera
setContext(context)
setup()
}
public func setup()
{
setupLight()
setupShadowUniformBuffer()
updateShadowUniforms()
}
func setupLight()
{
light.position = lightPosition
light.lookat(lightDirection)
lightViewMatrix = lookAt(light.position, light.position + light.forwardDirection, light.upDirection)
lightProjectionMatrix = orthographic(left: -10, right: 10, bottom: -10, top: 10, near: -10, far: 20)
shadowMatrix = lightProjectionMatrix * lightViewMatrix
}
func setupShadowUniformBuffer()
{
guard let context = self.context else { return }
let device = context.device
let alignedUniformsSize = ((MemoryLayout<ShadowUniforms>.size + 255) / 256) * 256
let uniformBufferSize = alignedUniformsSize * Satin.maxBuffersInFlight
guard let buffer = device.makeBuffer(length: uniformBufferSize, options: [MTLResourceOptions.storageModeShared]) else { return }
shadowUniformsBuffer = buffer
shadowUniformsBuffer.label = "Shadow Uniforms"
shadowUniforms = UnsafeMutableRawPointer(shadowUniformsBuffer.contents()).bindMemory(to: ShadowUniforms.self, capacity: 1)
}
func updateShadowUniforms()
{
if shadowUniforms != nil
{
shadowUniforms[0].shadowMatrix = shadowMatrix
}
}
func updateShadowUniformsBuffer()
{
if shadowUniformsBuffer != nil
{
uniformBufferIndex = (uniformBufferIndex + 1) % maxBuffersInFlight
let alignedUniformsSize = ((MemoryLayout<ShadowUniforms>.size + 255) / 256) * 256
uniformBufferOffset = alignedUniformsSize * uniformBufferIndex
shadowUniforms = UnsafeMutableRawPointer(shadowUniformsBuffer.contents() + uniformBufferOffset).bindMemory(to: ShadowUniforms.self, capacity: 1)
}
}
public func setContext(_ context: Context)
{
self.context = context
scene.context = context
}
public func update()
{
setupColorTexture()
setupDepthTexture()
setupStencilTexture()
setupShadowTexture()
setupShadowMaterial()
scene.update()
camera.update()
updateShadowUniformsBuffer()
}
public func drawShadows(parellelRenderEncoder: MTLParallelRenderCommandEncoder, object: Object)
{
if object is Mesh, let mesh = object as? Mesh, let material = shadowMaterial
{
guard let renderEncoder = parellelRenderEncoder.makeRenderCommandEncoder() else { return }
var pipeline: MTLRenderPipelineState!
if let meshShadowMaterial = mesh.shadowMaterial, let shadowPipeline = meshShadowMaterial.pipeline
{
pipeline = shadowPipeline
}
else if let shadowPipeline = material.pipeline
{
pipeline = shadowPipeline
}
let label = mesh.label
renderEncoder.pushDebugGroup(label)
renderEncoder.label = label
renderEncoder.setViewport(viewport)
mesh.update(camera: camera)
renderEncoder.setRenderPipelineState(pipeline)
material.bind(renderEncoder)
renderEncoder.setDepthBias(0.01, slopeScale: 1.0, clamp: 0.01)
renderEncoder.setCullMode(.front)
renderEncoder.setVertexBuffer(shadowUniformsBuffer, offset: uniformBufferOffset, index: VertexBufferIndex.ShadowUniforms.rawValue)
mesh.draw(renderEncoder: renderEncoder)
renderEncoder.popDebugGroup()
renderEncoder.endEncoding()
}
for child in object.children
{
drawShadows(parellelRenderEncoder: parellelRenderEncoder, object: child)
}
}
public func draw(renderPassDescriptor: MTLRenderPassDescriptor, commandBuffer: MTLCommandBuffer, renderTarget: MTLTexture)
{
if let context = self.context, context.sampleCount > 1
{
let resolveTexture = renderPassDescriptor.colorAttachments[0].resolveTexture
renderPassDescriptor.colorAttachments[0].resolveTexture = renderTarget
draw(renderPassDescriptor: renderPassDescriptor, commandBuffer: commandBuffer)
renderPassDescriptor.colorAttachments[0].resolveTexture = resolveTexture
}
else
{
let renderTexture = renderPassDescriptor.colorAttachments[0].texture
renderPassDescriptor.colorAttachments[0].texture = renderTarget
draw(renderPassDescriptor: renderPassDescriptor, commandBuffer: commandBuffer)
renderPassDescriptor.colorAttachments[0].texture = renderTexture
}
}
public func draw(renderPassDescriptor: MTLRenderPassDescriptor, commandBuffer: MTLCommandBuffer)
{
guard let context = self.context else { return }
if enableShadows
{
guard let parellelRenderEncoder = commandBuffer.makeParallelRenderCommandEncoder(descriptor: shadowRenderPassDescriptor) else { return }
parellelRenderEncoder.pushDebugGroup("Shadow Pass")
parellelRenderEncoder.label = "Shadow Encoder"
updateShadowUniforms()
drawShadows(parellelRenderEncoder: parellelRenderEncoder, object: scene)
parellelRenderEncoder.popDebugGroup()
parellelRenderEncoder.endEncoding()
}
let sampleCount = context.sampleCount
let depthPixelFormat = context.depthPixelFormat
renderPassDescriptor.colorAttachments[0].clearColor = clearColor
if autoClearColor
{
renderPassDescriptor.colorAttachments[0].loadAction = .clear
}
else
{
renderPassDescriptor.colorAttachments[0].loadAction = .load
}
if sampleCount > 1 {
renderPassDescriptor.colorAttachments[0].texture = colorTexture
}
else
{
renderPassDescriptor.colorAttachments[0].resolveTexture = nil
}
renderPassDescriptor.colorAttachments[0].storeAction = sampleCount > 1 ? .storeAndMultisampleResolve : .store
if let depthTexture = self.depthTexture
{
renderPassDescriptor.depthAttachment.texture = depthTexture
renderPassDescriptor.depthAttachment.loadAction = depthLoadAction
renderPassDescriptor.depthAttachment.storeAction = depthStoreAction
renderPassDescriptor.depthAttachment.clearDepth = clearDepth
#if os(macOS)
if depthPixelFormat == .depth32Float_stencil8
{
renderPassDescriptor.stencilAttachment.texture = depthTexture
}
else if let stencilTexture = self.stencilTexture
{
renderPassDescriptor.stencilAttachment.texture = stencilTexture
renderPassDescriptor.stencilAttachment.loadAction = stencilLoadAction
renderPassDescriptor.stencilAttachment.storeAction = stencilStoreAction
renderPassDescriptor.stencilAttachment.clearStencil = clearStencil
}
#elseif os(iOS) || os(tvOS)
if depthPixelFormat == .depth32Float_stencil8
{
renderPassDescriptor.stencilAttachment.texture = depthTexture
}
else if let stencilTexture = self.stencilTexture
{
renderPassDescriptor.stencilAttachment.texture = stencilTexture
renderPassDescriptor.stencilAttachment.loadAction = stencilLoadAction
renderPassDescriptor.stencilAttachment.storeAction = stencilStoreAction
renderPassDescriptor.stencilAttachment.clearStencil = clearStencil
}
#endif
}
guard let parellelRenderEncoder = commandBuffer.makeParallelRenderCommandEncoder(descriptor: renderPassDescriptor) else { return }
parellelRenderEncoder.pushDebugGroup("Main Pass")
parellelRenderEncoder.label = "Main Encoder"
preDraw?(parellelRenderEncoder)
draw(parellelRenderEncoder: parellelRenderEncoder, object: scene)
postDraw?(parellelRenderEncoder)
parellelRenderEncoder.popDebugGroup()
parellelRenderEncoder.endEncoding()
}
public func draw(parellelRenderEncoder: MTLParallelRenderCommandEncoder, object: Object)
{
if object is Mesh, let mesh = object as? Mesh, let material = mesh.material, let pipeline = material.pipeline
{
mesh.update(camera: camera)
if mesh.visible
{
guard let renderEncoder = parellelRenderEncoder.makeRenderCommandEncoder() else { return }
let label = mesh.label
renderEncoder.pushDebugGroup(label)
renderEncoder.label = label
renderEncoder.setViewport(viewport)
renderEncoder.setRenderPipelineState(pipeline)
if enableShadows
{
material.shadowTexture = shadowTexture
renderEncoder.setFragmentTexture(shadowTexture, index: FragmentTextureIndex.Shadow.rawValue)
}
material.bind(renderEncoder)
renderEncoder.setVertexBuffer(shadowUniformsBuffer, offset: uniformBufferOffset, index: VertexBufferIndex.ShadowUniforms.rawValue)
mesh.draw(renderEncoder: renderEncoder)
renderEncoder.popDebugGroup()
renderEncoder.endEncoding()
}
}
for child in object.children
{
draw(parellelRenderEncoder: parellelRenderEncoder, object: child)
}
}
public func resize(_ size: (width: Float, height: Float))
{
self.size = size
}
public func setupDepthTexture()
{
guard let context = self.context, updateDepthTexture else { return }
let sampleCount = context.sampleCount
let depthPixelFormat = context.depthPixelFormat
if depthPixelFormat != .invalid, size.width > 1, size.height > 1
{
let descriptor = MTLTextureDescriptor()
descriptor.pixelFormat = depthPixelFormat
descriptor.width = Int(size.width)
descriptor.height = Int(size.height)
descriptor.sampleCount = sampleCount
descriptor.textureType = sampleCount > 1 ? .type2DMultisample : .type2D
descriptor.usage = [.renderTarget, .shaderRead]
descriptor.storageMode = .private
descriptor.resourceOptions = .storageModePrivate
depthTexture = context.device.makeTexture(descriptor: descriptor)
depthTexture?.label = "Depth Texture"
updateDepthTexture = false
}
else
{
depthTexture = nil
}
}
public func setupStencilTexture()
{
guard let context = self.context, updateStencilTexture else { return }
let sampleCount = context.sampleCount
let stencilPixelFormat = context.stencilPixelFormat
if stencilPixelFormat != .invalid, size.width > 1, size.height > 1
{
let descriptor = MTLTextureDescriptor()
descriptor.pixelFormat = stencilPixelFormat
descriptor.width = Int(size.width)
descriptor.height = Int(size.height)
descriptor.sampleCount = sampleCount
descriptor.textureType = sampleCount > 1 ? .type2DMultisample : .type2D
descriptor.usage = [.renderTarget, .shaderRead]
descriptor.storageMode = .private
descriptor.resourceOptions = .storageModePrivate
stencilTexture = context.device.makeTexture(descriptor: descriptor)
stencilTexture?.label = "Stencil Texture"
updateStencilTexture = false
}
else
{
stencilTexture = nil
}
}
public func setupColorTexture()
{
guard let context = self.context, updateColorTexture else { return }
let sampleCount = context.sampleCount
let colorPixelFormat = context.colorPixelFormat
if colorPixelFormat != .invalid, size.width > 1, size.height > 1, sampleCount > 1 {
let descriptor = MTLTextureDescriptor()
descriptor.pixelFormat = colorPixelFormat
descriptor.width = Int(size.width)
descriptor.height = Int(size.height)
descriptor.sampleCount = sampleCount
descriptor.textureType = .type2DMultisample
descriptor.usage = [.renderTarget, .shaderRead]
descriptor.storageMode = .private
descriptor.resourceOptions = .storageModePrivate
colorTexture = context.device.makeTexture(descriptor: descriptor)
colorTexture?.label = "Color Texture"
updateColorTexture = false
}
else
{
colorTexture = nil
}
}
public func setupShadowMaterial()
{
if updateShadowMaterial, enableShadows
{
guard let context = self.context else { return }
let shadowMaterial = ShadowMaterial(simd_make_float4(0.0, 0.0, 0.0, 1.0))
shadowMaterial.context = Context(context.device, context.sampleCount, .invalid, context.depthPixelFormat, .invalid)
self.shadowMaterial = shadowMaterial
updateShadowMaterial = false
}
}
public func setupShadowTexture()
{
guard let context = self.context, updateShadowTexture else { return }
let sampleCount = context.sampleCount
let depthPixelFormat = context.depthPixelFormat
if depthPixelFormat != .invalid, size.width > 1, size.height > 1
{
let descriptor = MTLTextureDescriptor()
descriptor.pixelFormat = depthPixelFormat
descriptor.width = Int(size.width)
descriptor.height = Int(size.height)
descriptor.sampleCount = 1
descriptor.textureType = .type2D
descriptor.usage = [.shaderRead, .renderTarget]
descriptor.storageMode = .private
descriptor.resourceOptions = .storageModePrivate
shadowTexture = context.device.makeTexture(descriptor: descriptor)
shadowTexture?.label = "Shadow Texture"
if sampleCount > 1 {
let descriptor = MTLTextureDescriptor()
descriptor.pixelFormat = depthPixelFormat
descriptor.width = Int(size.width)
descriptor.height = Int(size.height)
descriptor.sampleCount = sampleCount
descriptor.textureType = .type2DMultisample
descriptor.usage = [.renderTarget]
descriptor.storageMode = .private
descriptor.resourceOptions = .storageModePrivate
let shadowMultisampleTexture = context.device.makeTexture(descriptor: descriptor)
shadowMultisampleTexture?.label = "Shadow Multisample Texture"
shadowRenderPassDescriptor.depthAttachment.texture = shadowMultisampleTexture
shadowRenderPassDescriptor.depthAttachment.resolveTexture = shadowTexture
}
else
{
shadowRenderPassDescriptor.depthAttachment.texture = shadowTexture
shadowRenderPassDescriptor.depthAttachment.resolveTexture = nil
}
shadowRenderPassDescriptor.depthAttachment.loadAction = .clear
shadowRenderPassDescriptor.depthAttachment.storeAction = sampleCount > 1 ? .storeAndMultisampleResolve : .store
shadowRenderPassDescriptor.depthAttachment.clearDepth = 1.0
updateShadowTexture = false
}
else
{
shadowTexture = nil
}
}
}
|
//
// ViperAssemblyProtocol.swift
// Translator
//
// Created by Dmitry Melnikov on 24/06/2019.
// Copyright © 2019 Дмитрий Мельников. All rights reserved.
//
import UIKit
/// All module configurators have to implement this protocol
protocol ViperAssemblyProtocol: class {
/// Prepare module with injection and return view controller
///
/// - Parameters:
/// - injection: application services
/// - completion: module callback
/// - Returns: module view controller
func make(with injection: ApplicationServicesProtocol?,
completion: ModuleCompletion?) -> UIViewController
}
|
//
// EcoPonto.swift
// Recicla Facil
//
// Created by aluno on 18/09/19.
// Copyright © 2019 aluno. All rights reserved.
//
import Foundation
class EcoPonto: Decodable {
var nome:String!
var endereco:String!
var bairro:String!
var latitude:Double!
var longitude:Double!
init(){}
init(nome:String,endereco:String,bairro:String,latitude:Double,longitude:Double){
self.nome = nome
self.endereco = endereco
self.bairro = bairro
self.latitude = latitude
self.longitude = longitude
}
}
|
public struct BuildAbortParams: Codable {
let abortReason: String
let abortWithSuccess, skipNotifications: Bool
enum CodingKeys: String, CodingKey {
case abortReason = "abort_reason"
case abortWithSuccess = "abort_with_success"
case skipNotifications = "skip_notifications"
}
}
|
//
// Created by Daniel Heredia on 2/27/18.
// Copyright © 2018 Daniel Heredia. All rights reserved.
//
// File System
import Foundation
class Entry {
var parent: Directory?
var name: String
let created: Date
var lastUpdate: Date
var lastAccess: Date
init(name: String, parent: Directory?) {
self.name = name
self.parent = parent
self.created = Date()
self.lastUpdate = Date()
self.lastAccess = Date()
}
func delete() -> Bool {
if let parent = self.parent{
return parent.deleteEntry(self)
} else {
return false
}
}
var fullPath: String {
if let parent = self.parent {
return parent.fullPath + "/" + self.name
} else {
return self.name
}
}
var size: Int {
return 0
}
}
// MARK: File
class File: Entry {
var content: String
var fileSize: Int
init(name: String, parent: Directory, content: String, size: Int) {
self.content = content
self.fileSize = size
super.init(name: name, parent: parent)
self.parent?.addEntry(self)
}
override var size: Int {
return self.fileSize
}
}
// MARK: Directory
class Directory: Entry {
var entries: [Entry]
override init(name: String, parent: Directory? = nil) {
entries = [Entry]()
super.init(name: name, parent: parent)
}
func addEntry(_ entry: Entry) {
self.entries.append(entry)
entry.parent = self
}
func deleteEntry(_ entry: Entry) -> Bool{
if let index = self.entries.index(where: { $0 === entry }) {
self.entries.remove(at: index)
return true
}
return false
}
override var size: Int {
var size = 0
for entry in self.entries {
size += entry.size
}
return size
}
var numberOfFiles: Int {
var number = 0
for entry in self.entries {
if let directory = entry as? Directory {
number += directory.numberOfFiles
} else {
number += 1
}
}
return number
}
}
|
//
// VcSettingsLayout.swift
// KayakFirst Ergometer E2
//
// Created by Balazs Vidumanszki on 2017. 12. 26..
// Copyright © 2017. Balazs Vidumanszki. All rights reserved.
//
import Foundation
class VcSettingsLayout: BaseLayout {
override func setView() {
contentView.addSubview(imgLogo)
contentView.addSubview(textFieldWebsite)
contentView.addSubview(textFieldTermsCondition)
contentView.addSubview(textFieldFeedback)
contentView.addSubview(labelVersion)
}
override func handlePortraitLayout(size: CGSize) {
imgLogo.snp.removeConstraints()
textFieldWebsite.snp.removeConstraints()
textFieldTermsCondition.snp.removeConstraints()
textFieldFeedback.snp.removeConstraints()
labelVersion.snp.removeConstraints()
imgLogo.snp.makeConstraints { (make) in
make.centerX.equalTo(contentView)
make.top.equalTo(contentView).inset(UIEdgeInsetsMake(margin, 0, 0, 0))
}
textFieldWebsite.snp.makeConstraints { (make) in
make.centerX.equalTo(contentView)
make.top.equalTo(imgLogo.snp.bottom).inset(UIEdgeInsetsMake(0, 0, -margin2 * 2, 0))
}
textFieldTermsCondition.snp.makeConstraints { (make) in
make.centerX.equalTo(contentView)
make.top.equalTo(textFieldWebsite.snp.bottom).inset(UIEdgeInsetsMake(0, 0, -margin2, 0))
}
textFieldFeedback.snp.makeConstraints { (make) in
make.centerX.equalTo(contentView)
make.top.equalTo(textFieldTermsCondition.snp.bottom).inset(UIEdgeInsetsMake(0, 0, -margin2, 0))
}
labelVersion.snp.makeConstraints { (make) in
make.centerX.equalTo(contentView)
make.bottom.equalTo(contentView).inset(UIEdgeInsetsMake(0, 0, margin, 0))
}
}
override func handleLandscapeLayout(size: CGSize) {
imgLogo.snp.removeConstraints()
textFieldWebsite.snp.removeConstraints()
textFieldTermsCondition.snp.removeConstraints()
textFieldFeedback.snp.removeConstraints()
labelVersion.snp.removeConstraints()
imgLogo.snp.makeConstraints { (make) in
make.centerX.equalTo(contentView)
make.top.equalTo(contentView)
}
textFieldWebsite.snp.makeConstraints { (make) in
make.centerX.equalTo(contentView)
make.top.equalTo(imgLogo.snp.bottom).inset(UIEdgeInsetsMake(0, 0, -margin05, 0))
}
textFieldTermsCondition.snp.makeConstraints { (make) in
make.centerX.equalTo(contentView)
make.top.equalTo(textFieldWebsite.snp.bottom).inset(UIEdgeInsetsMake(0, 0, -margin05, 0))
}
textFieldFeedback.snp.makeConstraints { (make) in
make.centerX.equalTo(contentView)
make.top.equalTo(textFieldTermsCondition.snp.bottom).inset(UIEdgeInsetsMake(0, 0, -margin05, 0))
}
labelVersion.snp.makeConstraints { (make) in
make.centerX.equalTo(contentView)
make.top.equalTo(textFieldFeedback.snp.bottom).inset(UIEdgeInsetsMake(0, 0, -margin05, 0))
make.bottom.equalTo(contentView).inset(UIEdgeInsetsMake(0, 0, margin05, 0))
}
}
//MARK: views
lazy var imgLogo: UIImageView! = {
let imageView = UIImageView()
let image = UIImage(named: "logo")
imageView.image = image
imageView.contentMode = .scaleAspectFit
return imageView
}()
lazy var textFieldWebsite: UITextField! = {
let textField = UITextField()
textField.setBottomBorder(Colors.colorWhite)
textField.textColor = Colors.colorWhite
textField.text = getString("app_link")
return textField
}()
lazy var textFieldTermsCondition: UITextField! = {
let textField = UITextField()
textField.setBottomBorder(Colors.colorWhite)
textField.textColor = Colors.colorWhite
textField.text = getString("user_terms_conditions_short")
return textField
}()
lazy var textFieldFeedback: UITextField! = {
let textField = UITextField()
textField.setBottomBorder(Colors.colorWhite)
textField.textColor = Colors.colorWhite
textField.text = getString("feedback_title")
return textField
}()
lazy var labelVersion: UILabel! = {
let label = UILabel()
label.text = getString("app_version") + " " + AppDelegate.versionString
label.textColor = Colors.colorGrey
return label
}()
}
|
//
// iOSTakeHomeChallengeTests.swift
// iOSTakeHomeChallengeTests
//
// Created by Oleksiy Chebotarov on 19/08/2021.
//
@testable import iOSTakeHomeChallenge
import XCTest
class iOSTakeHomeChallengeTests: XCTestCase {
var bookViewModel: BookViewModel!
var booksViewModel: BooksViewModelType!
var books: [Book]!
override func setUpWithError() throws {
let networkServiceLocal = NetworkServiceLocal(json: booksJson)
let localDataFetcher = NetworkDataFetcher(networkingService: networkServiceLocal)
booksViewModel = BooksViewModel(dataFetcher: localDataFetcher)
booksViewModel.books.bind { books in
if let books = books {
self.books = books
}
}
booksViewModel.fetchBooks()
}
override func tearDownWithError() throws {
booksViewModel = nil
bookViewModel = nil
books = nil
}
func testFetchResponseContainsValues() throws {
XCTAssertTrue(books.count > 0)
}
func testFirstItemInBooks() throws {
bookViewModel = BookViewModel(book: books[0])
XCTAssertEqual(bookViewModel.name, "A Game of Thrones")
XCTAssertEqual(bookViewModel.released, "Aug 1996")
XCTAssertEqual(bookViewModel.numberOfPages, "694 pages")
}
func testSecondItemInBooks() throws {
bookViewModel = BookViewModel(book: books[1])
XCTAssertEqual(bookViewModel.name, "A Clash of Kings")
XCTAssertEqual(bookViewModel.released, "Feb 1999")
XCTAssertEqual(bookViewModel.numberOfPages, "768 pages")
}
}
|
//
// PhotoManiaApp.swift
// PhotoMania
//
// Created by Christopher Delaney on 11/3/21.
//
import SwiftUI
@main
struct PhotoManiaApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
|
//
// SettingsOptionButtonCell.swift
//
// SwiftySettings
// Created by Tomasz Gebarowski on 07/08/15.
// Copyright © 2015 codica Tomasz Gebarowski <gebarowski at gmail.com>.
// All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import UIKit
class OptionsButtonCell : SettingsCell {
let selectedOptionLabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
override func updateConstraints() {
if !didSetupConstraints {
selectedOptionLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraints([
// Spacing Between Title and Selected UILabel
NSLayoutConstraint(item: selectedOptionLabel,
attribute: .left,
relatedBy: .greaterThanOrEqual,
toItem: textLabel!,
attribute: .right,
multiplier: 1.0,
constant: 15),
// Selected Option UILabel - Horizontal Constraints
NSLayoutConstraint(item: contentView,
attribute: .trailing,
relatedBy: .equal,
toItem: selectedOptionLabel,
attribute: .trailing,
multiplier: 1.0,
constant: 5),
// Selected Option UILabel - Vertical Constraints
NSLayoutConstraint(item: contentView,
attribute: .centerY,
relatedBy: .equal,
toItem: selectedOptionLabel,
attribute: .centerY,
multiplier: 1.0,
constant: 0)
])
}
super.updateConstraints()
}
override func setupViews() {
super.setupViews()
textLabel?.setContentHuggingPriority(UILayoutPriority.defaultHigh,
for: .horizontal)
selectedOptionLabel.setContentCompressionResistancePriority(UILayoutPriority.defaultHigh,
for: .horizontal)
contentView.addSubview(selectedOptionLabel)
}
override func configureAppearance() {
super.configureAppearance()
textLabel?.textColor = appearance?.cellTextColor
selectedOptionLabel.textColor = appearance?.cellSecondaryTextColor
contentView.backgroundColor = appearance?.cellBackgroundColor
accessoryView?.backgroundColor = appearance?.cellBackgroundColor
}
func load(_ item: OptionsButton) {
self.textLabel?.text = item.title
self.selectedOptionLabel.text = item.selectedOptionTitle
self.accessoryType = .disclosureIndicator
if let image = item.icon {
self.imageView?.image = image
}
configureAppearance()
setNeedsUpdateConstraints()
}
}
|
import Foundation
import Yams
import Quick
import Nimble
@testable import SwaggerKit
final class SpecSecuritySchemeTests: QuickSpec {
// MARK: - Instance Methods
override func spec() {
var securityScheme: SpecSecurityScheme!
var securitySchemeYAML: String!
describe("Invalid type of authentication") {
beforeEach {
securitySchemeYAML = SpecSecuritySchemeSeeds.invalidTypeYAML
}
it("should not be decoded") {
do {
_ = try YAMLDecoder.test.decode(
SpecSecurityScheme.self,
from: securitySchemeYAML
)
fail("Test encountered unexpected behavior")
} catch {
expect(error).to(beAKindOf(DecodingError.self))
}
}
}
describe("API Key authentication") {
beforeEach {
securityScheme = SpecSecuritySchemeSeeds.apiKey
securitySchemeYAML = SpecSecuritySchemeSeeds.apiKeyYAML
}
it("should be correctly decoded from YAML string") {
do {
let decodedSecurityScheme = try YAMLDecoder.test.decode(
SpecSecurityScheme.self,
from: securitySchemeYAML
)
expect(decodedSecurityScheme).to(equal(securityScheme))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
it("should be correctly encoded to YAML string") {
do {
let encodedSecuritySchemeYAML = try YAMLEncoder.test.encode(securityScheme)
expect(encodedSecuritySchemeYAML).to(equal(try securitySchemeYAML.yamlSorted()))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
}
describe("OAuth 2.0 authentication") {
beforeEach {
securityScheme = SpecSecuritySchemeSeeds.oauth2
securitySchemeYAML = SpecSecuritySchemeSeeds.oauth2YAML
}
it("should be correctly decoded from YAML string") {
do {
let decodedSecurityScheme = try YAMLDecoder.test.decode(
SpecSecurityScheme.self,
from: securitySchemeYAML
)
expect(decodedSecurityScheme).to(equal(securityScheme))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
it("should be correctly encoded to YAML string") {
do {
let encodedSecuritySchemeYAML = try YAMLEncoder.test.encode(securityScheme)
expect(encodedSecuritySchemeYAML).to(equal(try securitySchemeYAML.yamlSorted()))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
}
describe("Basic authentication") {
beforeEach {
securityScheme = SpecSecuritySchemeSeeds.basic
securitySchemeYAML = SpecSecuritySchemeSeeds.basicYAML
}
it("should be correctly decoded from YAML string") {
do {
let decodedSecurityScheme = try YAMLDecoder.test.decode(
SpecSecurityScheme.self,
from: securitySchemeYAML
)
expect(decodedSecurityScheme).to(equal(securityScheme))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
it("should be correctly encoded to YAML string") {
do {
let encodedSecuritySchemeYAML = try YAMLEncoder.test.encode(securityScheme)
expect(encodedSecuritySchemeYAML).to(equal(try securitySchemeYAML.yamlSorted()))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
}
describe("Bearer authentication") {
beforeEach {
securityScheme = SpecSecuritySchemeSeeds.bearer
securitySchemeYAML = SpecSecuritySchemeSeeds.bearerYAML
}
it("should be correctly decoded from YAML string") {
do {
let decodedSecurityScheme = try YAMLDecoder.test.decode(
SpecSecurityScheme.self,
from: securitySchemeYAML
)
expect(decodedSecurityScheme).to(equal(securityScheme))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
it("should be correctly encoded to YAML string") {
do {
let encodedSecuritySchemeYAML = try YAMLEncoder.test.encode(securityScheme)
expect(encodedSecuritySchemeYAML).to(equal(try securitySchemeYAML.yamlSorted()))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
}
describe("Digest authentication") {
beforeEach {
securityScheme = SpecSecuritySchemeSeeds.digest
securitySchemeYAML = SpecSecuritySchemeSeeds.digestYAML
}
it("should be correctly decoded from YAML string") {
do {
let decodedSecurityScheme = try YAMLDecoder.test.decode(
SpecSecurityScheme.self,
from: securitySchemeYAML
)
expect(decodedSecurityScheme).to(equal(securityScheme))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
it("should be correctly encoded to YAML string") {
do {
let encodedSecuritySchemeYAML = try YAMLEncoder.test.encode(securityScheme)
expect(encodedSecuritySchemeYAML).to(equal(try securitySchemeYAML.yamlSorted()))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
}
describe("OpenID Connect authentication") {
beforeEach {
securityScheme = SpecSecuritySchemeSeeds.openIDConnect
securitySchemeYAML = SpecSecuritySchemeSeeds.openIDConnectYAML
}
it("should be correctly decoded from YAML string") {
do {
let decodedSecurityScheme = try YAMLDecoder.test.decode(
SpecSecurityScheme.self,
from: securitySchemeYAML
)
expect(decodedSecurityScheme).to(equal(securityScheme))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
it("should be correctly encoded to YAML string") {
do {
let encodedSecuritySchemeYAML = try YAMLEncoder.test.encode(securityScheme)
expect(encodedSecuritySchemeYAML).to(equal(try securitySchemeYAML.yamlSorted()))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
}
describe(".extensions") {
beforeEach {
securityScheme = SpecSecuritySchemeSeeds.openIDConnect
}
it("should return extensions") {
expect(securityScheme.extensions as? [String: Bool]).to(equal(["private": true]))
}
it("should modify extensions") {
securityScheme.extensions["private"] = false
expect(securityScheme.extensions as? [String: Bool]).to(equal(["private": false]))
}
}
}
}
|
//
// HttpUrl.swift
// LR61
//
// Created by Marty on 19/05/2018.
// Copyright © 2018 Marty. All rights reserved.
//
import Foundation
class HttpUrl {
public private(set) var urlProtocol: Protocol!
public private(set) var urlPort: Int!
public private(set) var urlHost = ""
public private(set) var urlDoc = ""
public private(set) var url: URL!
init(withUrl strUrl: String) throws {
func setDoc() {
let protocolSuffixSize = 3
let hostSuffixSize = 1
var portOffset = 0
if url.port != nil {
portOffset += String(urlPort).count + 1
}
let docOffset = urlProtocol.rawValue.count + protocolSuffixSize +
urlHost.count + hostSuffixSize + portOffset
if docOffset < strUrl.count {
let docLowerBound = strUrl.index(strUrl.startIndex, offsetBy: docOffset)
urlDoc = String(strUrl[docLowerBound..<strUrl.endIndex])
}
let docSeparator = "/"
if urlDoc.isEmpty {
urlDoc = docSeparator
}
let firstChar = urlDoc[urlDoc.startIndex]
urlDoc = (String(firstChar) == docSeparator) ? urlDoc : (docSeparator + urlDoc)
}
// url
guard let url = URL(string: strUrl) else {
throw HttpUrlError.incorrectUrl
}
self.url = url
// protocol
guard let urlProtocol = Protocol(rawValue: (url.scheme ?? "").uppercased()) else {
throw HttpUrlError.incorrectProtocol(url.scheme ?? "")
}
self.urlProtocol = urlProtocol
// port
let theFirstPortNumber = 1
let theLastPortNumber = 65_535
urlPort = url.port ?? urlProtocol.defaultPort()
if urlPort < theFirstPortNumber || urlPort > theLastPortNumber {
throw HttpUrlError.incorrectPort(urlPort)
}
// host
guard let urlHost = url.host, !urlHost.isEmpty else {
throw HttpUrlError.incorrectHost
}
self.urlHost = urlHost
//doc
setDoc()
}
init(withHost host: String, document: String, andProtocol protpcol: Protocol) throws {
// doc
let docSeparator = "/"
let firstChar = document[document.startIndex]
self.urlDoc = (String(firstChar) == docSeparator) ? document : (docSeparator + document)
// protocol
guard let urlProtocol = Protocol(rawValue: protpcol.rawValue.uppercased()) else {
throw HttpUrlError.incorrectProtocol(protpcol.rawValue)
}
self.urlProtocol = urlProtocol
self.urlPort = urlProtocol.defaultPort()
// host
guard !host.isEmpty else {
throw HttpUrlError.incorrectHost
}
self.urlHost = host
// url
guard let url = URL(string: self.urlProtocol.rawValue.lowercased() + "://" + self.urlHost + ":" + String(self.urlPort) + self.urlDoc) else {
throw HttpUrlError.incorrectUrl
}
self.url = url
}
init(withHost host: String, document: String, port: Int, andProtocol protpcol: Protocol) throws {
// doc
let docSeparator = "/"
let firstChar = document[document.startIndex]
self.urlDoc = (String(firstChar) == docSeparator) ? document : (docSeparator + document)
// protocol
guard let urlProtocol = Protocol(rawValue: protpcol.rawValue.uppercased()) else {
throw HttpUrlError.incorrectProtocol(protpcol.rawValue)
}
self.urlProtocol = urlProtocol
self.urlPort = urlProtocol.defaultPort()
// port
let theFirstPortNumber = 1
let theLastPortNumber = 65_535
if urlPort < theFirstPortNumber || urlPort > theLastPortNumber {
throw HttpUrlError.incorrectPort(urlPort)
}
self.urlPort = port
// host
guard !host.isEmpty else {
throw HttpUrlError.incorrectHost
}
self.urlHost = host
// url
guard let url = URL(string: self.urlProtocol.rawValue.lowercased() + "://" + self.urlHost + ":" + String(self.urlPort) + self.urlDoc) else {
throw HttpUrlError.incorrectHost
}
self.url = url
}
}
|
//
// MedicineDetailsVC.swift
// szenzormodalitasok
//
// Created by Tóth Zoltán on 2021. 05. 08..
// Copyright © 2021. Tóth Zoltán. All rights reserved.
//
// Imports
import UIKit
// Medicines details page - UIViewController
class MedicineDetailsViewController: UIViewController, ProvidingInjecting {
// Struct
struct Args {
var medicineModel: MedicineModel
var pageSource: PageSource
}
private(set) lazy var favouriteProvider: FavouriteProviding = {
favouriteInject()
}()
// Variables
var medicineDetailArgs = Args(medicineModel: MedicineModel.empty, pageSource: .medicines)
// IB Outlets
@IBOutlet weak var medicineDetailView: UIView!
@IBOutlet weak var factoryName: UILabel!
@IBOutlet weak var activeSubstanceName: UILabel!
@IBOutlet weak var package: UILabel!
@IBOutlet weak var administrationMethod: UILabel!
@IBOutlet weak var suggestionForUseButton: CustomMedicineDetailsButton!
@IBOutlet weak var recommendedDosageButton: CustomMedicineDetailsButton!
@IBOutlet weak var warningDetailButton: CustomMedicineDetailsButton!
@IBOutlet weak var dosageButton: CustomDosageButton!
// viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
title = medicineDetailArgs.medicineModel.medicineName
factoryName.text = medicineDetailArgs.medicineModel.factoryMedicineName
activeSubstanceName.text = medicineDetailArgs.medicineModel.activeSubstanceName
package.text = medicineDetailArgs.medicineModel.package
administrationMethod.text = medicineDetailArgs.medicineModel.administrationMethod
suggestionForUseButton.setButtonTitle(NSLocalizedString("medicineDetailSuggestionForUseButton.title", comment: ""))
recommendedDosageButton.setButtonTitle(NSLocalizedString("medicineDetailRecommendedDosageButton.title", comment: "") + ": " + medicineDetailArgs.medicineModel.administrationMethod)
warningDetailButton.setButtonTitle(NSLocalizedString("medicineDetailWarningButton.title", comment: ""))
dosageButton.setButtonTitle(NSLocalizedString("medicineDetailDosageButton.title", comment: ""))
medicineDetailView.backgroundColor = .white
if medicineDetailArgs.pageSource == .favourites {
navigationItem.rightBarButtonItem = nil
} else {
}
}
// Functions
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let detailViewer = segue.destination as? MoreDetailViewController, let detail = sender as? String {
detailViewer.medicineDetailArgs.oneMedicineDetail = detail
} else if let dosageViewer = segue.destination as? DosageViewController, let detail = sender as? String {
dosageViewer.medicineNameArgs.medicineName = detail
}
}
// IB Actions
@IBAction func suggestionForUseButtonTapped(_ sender: Any) {
performSegue(withIdentifier: "showDetail", sender: medicineDetailArgs.medicineModel.suggestionForUse)
}
@IBAction func recommendedDosageButtonTapped(_ sender: Any) {
performSegue(withIdentifier: "showDetail", sender: medicineDetailArgs.medicineModel.recommendedDosage)
}
@IBAction func warningDetailButtonTapped(_ sender: Any) {
performSegue(withIdentifier: "showDetail", sender: medicineDetailArgs.medicineModel.warningsContraindications)
}
@IBAction func dosageButtonTapped(_ sender: Any) {
performSegue(withIdentifier: "showDosagePage", sender: medicineDetailArgs.medicineModel.medicineName)
}
@IBAction func addToFavourites(_ sender: Any) {
favouriteProvider.add(medicineID: medicineDetailArgs.medicineModel.medicineID)
}
}
|
//
// ServiceManager.swift
// BigProject
//
// Created by Tran Trung Hieu on 11/14/15.
// Copyright © 2015 3SI. All rights reserved.
//
import Foundation
import Alamofire
public class ServiceManager {
class var sharedInstance: ServiceManager {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: ServiceManager? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = ServiceManager()
}
return Static.instance!
}
public func getReview(){
let manager = Alamofire.Manager.sharedInstance
let urlString = "https://zilyo.p.mashape.com/search?isinstantbook=true&nelatitude=22.37&nelongitude=-154.48000000000002&provider=airbnb%2Chousetrip&swlatitude=18.55&swlongitude=-160.52999999999997"
let headers = ["Accept": "application/json","X-Mashape-Key": "tKxQHTDGAbmsh3dKmcUkZOz0utf1p1ZyJ4OjsnDxjp0ybJQGxP"]
manager.request(.GET, urlString, headers: headers).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)")
}
}
}
public func getInformationOfItemVia(barCodeString: String, completion: ((list : NSDictionary!) -> Void)?) {
//--- block code.
let manager = Alamofire.Manager.sharedInstance
// let urlString = "https://zilyo.p.mashape.com/search?isinstantbook=true&nelatitude=22.37&nelongitude=-154.48000000000002"
let headers = ["Accept": "application/json","X-Mashape-Key": "tKxQHTDGAbmsh3dKmcUkZOz0utf1p1ZyJ4OjsnDxjp0ybJQGxP"]
//@"https://zilyo.p.mashape.com/search?isinstantbook=true&nelatitude=22.37&nelongitude=-154.48000000000002&provider=airbnb%2Chousetrip&swlatitude=18.55&swlongitude=-160.52999999999997"];
let params = [ "latitude" : 21.027764,"longitude":105.834160] as Dictionary<String, AnyObject>
manager.request(.GET, "https://zilyo.p.mashape.com/search",parameters: params, headers: headers).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)")
if completion != nil {
completion! (list: JSON as! NSDictionary)
}
}
}
}
}
|
//
// SongCell.swift
// MusicApp
//
// Copyright © 2019 Bedu. All rights reserved.
//
import UIKit
class SongCell: UITableViewCell {
@IBOutlet weak var albumImage: UIImageView!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var album: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
name.textColor = .white
album.textColor = TextGrayColor
self.backgroundColor = .clear
// Color selection
let selectedBackgroundView = UIView()
selectedBackgroundView.backgroundColor = greenSelectedCell
self.selectedBackgroundView = selectedBackgroundView
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// CasePersionViewController.swift
// huicheng
//
// Created by lvxin on 2018/4/13.
// Copyright © 2018年 lvxin. All rights reserved.
// 委托人 对方当事人 页面
import UIKit
typealias CasePersionViewControllerBlock = (_ pn:String,_ pc:String,_ pp:String,_ pz:String,_ pj:String,_ pd:String, _ pa:String)->()
enum CasePersionViewControllertype {
//委托人 对方当事人
case principal_detail,principal_add, opposite_detail,opposit_add
}
class CasePersionViewController: BaseViewController,UITableViewDataSource,UITableViewDelegate,TitleTableViewCellDelegate {
var type : CasePersionViewControllertype!
var nameArr : [String] = ["委托人","联系人","电话","邮编","职务","身份证号","联系地址",]
var dataArr : Array<String> = []
var caseType : String = ""
var alertController : UIAlertController!
let mainTabelView : UITableView = UITableView()
let request : WorkRequestVC = WorkRequestVC()
var sureBlock : CasePersionViewControllerBlock!
var pnStr : String = ""
var pcStr : String = ""
var ppStr : String = ""
var pzStr : String = ""
var pjStr : String = ""
var pdStr : String = ""
var paStr : String = ""
// MARK: - life
override func viewWillLayoutSubviews() {
mainTabelView.snp.makeConstraints { (make) in
make.top.equalTo(self.view).offset(0)
make.left.right.equalTo(self.view).offset(0)
make.bottom.equalTo(self.view).offset(0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = viewBackColor
self.navigationBar_leftBtn_image(image: #imageLiteral(resourceName: "pub_arrow"))
if type == .principal_detail {
self.navigation_title_fontsize(name: "委托人情况", fontsize: 18)
if caseType == "4" {
nameArr = ["委托人","联系人","电话","邮编","职务","联系地址",]
} else if caseType == "3"{
nameArr = ["委托人","当事人","电话","邮编","职务","身份证号","联系地址",]
}
} else if type == .principal_add {
self.navigation_title_fontsize(name: "委托人情况", fontsize: 18)
self.navigationBar_rightBtn_title(name: "确定")
if caseType == "4" {
nameArr = ["委托人","联系人","电话","邮编","职务","联系地址",]
dataArr.append(self.pnStr)
dataArr.append(self.pcStr)
dataArr.append( self.ppStr)
dataArr.append(self.pzStr)
dataArr.append(self.pjStr)
dataArr.append(self.paStr)
} else if caseType == "3"{
nameArr = ["委托人","当事人","电话","邮编","职务","身份证号","联系地址",]
dataArr.append(self.pnStr)
dataArr.append(self.pcStr)
dataArr.append( self.ppStr)
dataArr.append(self.pzStr)
dataArr.append(self.pjStr)
dataArr.append( self.pdStr)
dataArr.append(self.paStr)
} else {
dataArr.append(self.pnStr)
dataArr.append(self.pcStr)
dataArr.append( self.ppStr)
dataArr.append(self.pzStr)
dataArr.append(self.pjStr)
dataArr.append( self.pdStr)
dataArr.append(self.paStr)
}
} else if type == .opposite_detail {
self.navigation_title_fontsize(name: "对方当事人情况", fontsize: 18)
nameArr.remove(at: 5)
} else{
self.navigation_title_fontsize(name: "对方当事人情况", fontsize: 18)
self.navigationBar_rightBtn_title(name: "确定")
nameArr.remove(at: 5)
dataArr.append(self.pnStr)
dataArr.append(self.pcStr)
dataArr.append( self.ppStr)
dataArr.append(self.pzStr)
dataArr.append(self.pjStr)
dataArr.append(self.paStr)
}
self.creatUI()
}
// MARK: - UI
func creatUI() {
mainTabelView.backgroundColor = UIColor.clear
mainTabelView.delegate = self;
mainTabelView.dataSource = self;
mainTabelView.tableFooterView = UIView()
mainTabelView.separatorStyle = .none
mainTabelView.showsVerticalScrollIndicator = false
mainTabelView.showsHorizontalScrollIndicator = false
mainTabelView.backgroundView?.backgroundColor = .clear
mainTabelView.register(UINib.init(nibName: "TitleTableViewCell", bundle: nil), forCellReuseIdentifier: TitleTableViewCellID)
self.view.addSubview(mainTabelView)
}
// MARK: - delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : TitleTableViewCell = tableView.dequeueReusableCell(withIdentifier: TitleTableViewCellID, for: indexPath) as! TitleTableViewCell
cell.delegate = self
cell.tag = indexPath.row
if indexPath.row < nameArr.count {
cell.setData_caseDetail(titleStr: nameArr[indexPath.row], contentStr: dataArr[indexPath.row],indexPath : indexPath)
}
if indexPath.row == 2 || indexPath.row == 3 {
cell.textField.keyboardType = .numberPad
} else {
cell.textField.keyboardType = .default
}
if type == .principal_detail || type == .opposite_detail{
cell.isUserInteractionEnabled = false
} else {
cell.isUserInteractionEnabled = true
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return TitleTableViewCellH
}
func endEdite(inputStr: String, tagNum: Int) {
HCLog(message: inputStr)
HCLog(message: tagNum)
if self.type == .principal_add {
if caseType == "4" {
if tagNum == 0 {
pnStr = inputStr
} else if tagNum == 1 {
pcStr = inputStr
} else if tagNum == 2 {
ppStr = inputStr
} else if tagNum == 3 {
pzStr = inputStr
} else if tagNum == 4 {
pjStr = inputStr
} else if tagNum == 5 {
paStr = inputStr
}
} else {
if tagNum == 0 {
pnStr = inputStr
} else if tagNum == 1 {
pcStr = inputStr
} else if tagNum == 2 {
ppStr = inputStr
} else if tagNum == 3 {
pzStr = inputStr
} else if tagNum == 4 {
pjStr = inputStr
} else if tagNum == 5 {
pdStr = inputStr
} else if tagNum == 6 {
paStr = inputStr
}
}
} else {
if tagNum == 0 {
pnStr = inputStr
} else if tagNum == 1 {
pcStr = inputStr
} else if tagNum == 2 {
ppStr = inputStr
} else if tagNum == 3 {
pzStr = inputStr
} else if tagNum == 4 {
pjStr = inputStr
} else if tagNum == 5 {
paStr = inputStr
}
}
}
override func navigationLeftBtnClick() {
if self.type == .principal_detail || self.type == .opposite_detail {
self.navigationController?.popViewController(animated: true)
} else {
alertController = UIAlertController(title: nil, message: "是否放弃本次记录", preferredStyle: .alert)
let actcion1 = UIAlertAction(title: "确定", style: .default) { (aciton) in
self.navigationController?.popViewController(animated: true)
}
let actcion2 = UIAlertAction(title: "取消", style: .cancel) { (aciton) in
self.alertController.dismiss(animated: true, completion: {
})
}
alertController.addAction(actcion1)
alertController.addAction(actcion2)
self.present(alertController, animated: true, completion: nil)
}
}
override func navigationRightBtnClick() {
HCLog(message: "确定")
self.view.endEditing(true)
self.sureBlock(self.pnStr ,self.pcStr ,self.ppStr, self.pzStr,self.pjStr,self.pdStr, self.paStr)
self.navigationController?.popViewController(animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// MonitorTask.swift
// Statbar
//
// Copyright © 2017 bsdelf. All rights reserved.
// Copyright © 2016 郭佳哲. All rights reserved.
//
import Foundation
open class SystemMonitor: NSObject {
let interval: TimeInterval
var lastInBytes: Double = 0
var lastOutBytes: Double = 0
var networkMonitor: UnsafeMutableRawPointer?
var timer: Timer? = nil
var statusItemView: StatusItemView? = nil
init(interval: TimeInterval) {
self.interval = interval
}
func start() {
try? SMCKit.open();
self.lastInBytes = 0
self.lastOutBytes = 0
self.networkMonitor = UnsafeMutableRawPointer(NetworkMonitorCreate())
self.timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(self.updateStats), userInfo: nil, repeats: true)
}
func stop() {
self.timer?.invalidate()
self.timer = nil
NetworkMonitorDestroy(self.networkMonitor);
_ = SMCKit.close();
}
@objc func updateStats() {
let coreTemp = try? Int(SMCKit.temperature(TemperatureSensors.CPU_0_PROXIMITY.code))
let fanSpeed = try? SMCKit.fanCurrentSpeed(0)
var upSpeed: Double?
var downSpeed: Double?
let stats = NetworkMonitorStats(self.networkMonitor)
if lastInBytes > 0 && lastOutBytes > 0 {
upSpeed = (Double(stats.obytes) - self.lastOutBytes) / self.interval
downSpeed = (Double(stats.ibytes) - self.lastInBytes) / self.interval
}
self.lastInBytes = Double(stats.ibytes);
self.lastOutBytes = Double(stats.obytes);
self.statusItemView?.updateMetrics(up: upSpeed, down: downSpeed, coreTemp: coreTemp, fanSpeed: fanSpeed);
}
}
|
import AudioKit
import AudioKitUI
import SoundpipeAudioKit
import SwiftUI
import AudioToolbox
struct DynamicOscillatorData {
var isPlaying: Bool = false
var frequency: AUValue = 440
var amplitude: AUValue = 0.1
var rampDuration: AUValue = 1
}
class DynamicOscillatorConductor: ObservableObject, KeyboardDelegate {
let engine = AudioEngine()
func noteOn(note: MIDINoteNumber) {
data.isPlaying = true
data.frequency = note.midiNoteToFrequency()
}
func noteOff(note: MIDINoteNumber) {
data.isPlaying = false
}
@Published var data = DynamicOscillatorData() {
didSet {
if data.isPlaying {
osc.start()
osc.$frequency.ramp(to: data.frequency, duration: data.rampDuration)
osc.$amplitude.ramp(to: data.amplitude, duration: data.rampDuration)
} else {
osc.amplitude = 0.0
}
}
}
var osc = DynamicOscillator()
init() {
engine.output = osc
}
func start() {
osc.amplitude = 0.2
do {
try engine.start()
} catch let err {
Log(err)
}
}
func stop() {
data.isPlaying = false
osc.stop()
engine.stop()
}
}
struct DynamicOscillatorView: View {
@StateObject var conductor = DynamicOscillatorConductor()
var body: some View {
VStack {
Text(self.conductor.data.isPlaying ? "STOP" : "START").onTapGesture {
self.conductor.data.isPlaying.toggle()
}
HStack {
Spacer()
Text("Sine").onTapGesture {
self.conductor.osc.setWaveform(Table(.sine))
}
Spacer()
Text("Square").onTapGesture {
self.conductor.osc.setWaveform(Table(.square))
}
Spacer()
Text("Triangle").onTapGesture {
self.conductor.osc.setWaveform(Table(.triangle))
}
Spacer()
Text("Sawtooth").onTapGesture {
self.conductor.osc.setWaveform(Table(.sawtooth))
}
Spacer()
}
ParameterSlider(text: "Frequency",
parameter: self.$conductor.data.frequency,
range: 220...880).padding()
ParameterSlider(text: "Amplitude",
parameter: self.$conductor.data.amplitude,
range: 0 ... 1).padding()
ParameterSlider(text: "Ramp Duration",
parameter: self.$conductor.data.rampDuration,
range: 0...10).padding()
NodeOutputView(conductor.osc)
KeyboardControl(firstOctave: 0,
octaveCount: 2,
polyphonicMode: false,
delegate: conductor)
}.navigationBarTitle(Text("Dynamic Oscillator"))
.onAppear {
self.conductor.start()
}
.onDisappear {
self.conductor.stop()
}
}
}
struct DynamicOscillatorView_Previews: PreviewProvider {
static var previews: some View {
DynamicOscillatorView()
}
}
|
//
// EntityMapping.swift
// TaskTimer
//
// Created by Sam Dean on 20/12/2016.
// Copyright © 2016 deanWombourne. All rights reserved.
//
import Foundation
extension Client: EntityMappable {
typealias EntityType = ClientEntity
static func from(entity: ClientEntity) -> Client {
return Client(id: entity.id!, name: entity.name!)
}
}
extension Project: EntityMappable {
typealias EntityType = ProjectEntity
static func from(entity: ProjectEntity) -> Project {
return Project(id: entity.id!, name: entity.name!)
}
}
extension Task: EntityMappable {
typealias EntityType = TaskEntity
static func from(entity: TaskEntity) -> Task {
return Task(id: entity.id!, name: entity.name!)
}
}
extension TimeSlice: EntityMappable {
typealias EntityType = TimeSliceEntity
static func from(entity: TimeSliceEntity) -> TimeSlice {
return TimeSlice(id: entity.id!,
start: entity.start! as Date,
end: entity.end as? Date)
}
}
|
//
// ViewController.swift
// testCollectionViewPerformance
//
// Created by Naoyuki Seido on 2017/03/11.
// Copyright © 2017 Naoyuki Seido. All rights reserved.
//
import Cocoa
class ViewController: NSViewController,NSCollectionViewDataSource, NSCollectionViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@IBOutlet weak var collectionView: MyCollectionView!
var ensureVisibleTarget : IndexPath? = nil
var preResizeScrollPoint : CGFloat = 0;
@IBAction func changedSize(_ sender: NSSlider) {
let l = self.collectionView.collectionViewLayout as! NSCollectionViewFlowLayout
if(NSApplication.shared().currentEvent?.type == .leftMouseDown) {
let pt = self.collectionView.enclosingScrollView?.convert(NSPoint(x: 1,y: 1), to: self.collectionView)
preResizeScrollPoint = pt!.y / self.collectionView.bounds.height
ensureVisibleTarget = self.collectionView.indexPathForItem(at: pt!)
}
self.collectionView.ignoreLayout = true
l.itemSize = NSSize(width: CGFloat(sender.floatValue), height: CGFloat(sender.floatValue))
self.collectionView.ignoreLayout = false
let finished = NSApplication.shared().currentEvent?.type == .leftMouseUp
if(finished) {
self.collectionView.reloadData()
}else {
DispatchQueue.main.async {
self.collectionView.needsLayout = true
let sp = NSPoint(x: 1.0, y: self.preResizeScrollPoint*self.collectionView.bounds.height)
self.collectionView.scroll(sp)
}
}
}
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return 2000
}
var dataList :Array<Dictionary<String, Any?>?> = Array<Dictionary<String, Any?>?>(repeating: nil, count: 2000)
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item : CollectionViewItem? = collectionView.makeItem(withIdentifier: "CollectionViewItem", for: indexPath) as? CollectionViewItem
var data = dataList[indexPath.item]
if data == nil {
let path = "~/testimage/"+String(indexPath.item)+".png"
data = [
"imageUrl" : NSString(string: path).expandingTildeInPath
]
dataList[indexPath.item] = data;
}
if let i = data?["imageUrl"] as? String {
item?.imagePath = i
}
return item!
}
}
|
//
// ScanViewController.swift
//
import UIKit
import AVFoundation
class ScanViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
var session: AVCaptureSession! //输入输出的中间桥梁
var myInput: AVCaptureDeviceInput! //创建输入流
var myOutput: AVCaptureMetadataOutput! //创建输出流
var bgView = UIView()
var barcodeView = UIView()
var timer = Timer()
var scanLine = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
// 导航栏标题
navigationItem.title = "扫描二维码"
// 设置定时器,延迟2秒启动
self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(moveScannerLayer(_:)), userInfo: nil, repeats: true)
// 初始化链接对象
self.session = AVCaptureSession.init()
// 设置高质量采集率
self.session.canSetSessionPreset(AVCaptureSessionPresetHigh)
// 获取摄像设备
let device: AVCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
// 捕捉异常,并处理
do {
self.myInput = try AVCaptureDeviceInput.init(device: device)
self.myOutput = AVCaptureMetadataOutput.init()
self.session.addInput(self.myInput)
self.session.addOutput(self.myOutput)
} catch {
print("error")
}
// 创建预览视图
self.createBackGroundView()
// 设置扫描范围(横屏)
self.myOutput.rectOfInterest = CGRect(x: 0.35, y: 0.2, width: UIScreen.main.bounds.width * 0.6 / UIScreen.main.bounds.height, height: 0.6)
// 设置扫码支持的编码格式(如下设置条形码和二维码兼容)
myOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code]
// 创建串行队列
let dispatchQueue = DispatchQueue(label: "queue", attributes: [])
// 设置输出流的代理
self.myOutput.setMetadataObjectsDelegate(self, queue: dispatchQueue)
// 创建预览图层
let myLayer = AVCaptureVideoPreviewLayer.init(session: self.session)
myLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill // 设置预览图层的填充方式
myLayer?.frame = self.view.layer.bounds // 设置预览图层的frame
self.bgView.layer.insertSublayer(myLayer!, at: 0) // 将预览图层(摄像头画面)插入到预览视图的最底部
// 开始扫描
self.session.startRunning()
self.timer.fire()
}
// 扫描结果,代理
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
if metadataObjects != nil && metadataObjects.count > 0 {
// 停止扫描
self.session.stopRunning()
timer.invalidate()
// 获取第一个
let metaData = metadataObjects.first as! AVMetadataMachineReadableCodeObject
let url = metaData.stringValue!
print(url)
DispatchQueue.main.async(execute: {
// 扫描到之后
// 检查网址是否合法(以 http:// 或 https:// 开头)
if url.hasPrefix("http://") || url.hasPrefix("https://") {
// 网址有效,发送通知
let nc = NotificationCenter.default
nc.post(name: myNotification, object: nil, userInfo: ["url": url, "type": "scan"])
} else {
// 网址无效,弹框提示
let ac = UIAlertController(title: "网址无效", message: url, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "确定", style: .default))
self.present(ac, animated: true)
}
// 关闭当前页
_ = self.navigationController?.popViewController(animated: true)
})
}
}
// 创建预览视图
func createBackGroundView() {
self.bgView.frame = UIScreen.main.bounds
self.bgView.backgroundColor = UIColor.black
self.view.addSubview(self.bgView)
// 灰色蒙版
let topView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height * 0.35))
let leftView = UIView(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.height * 0.35, width: UIScreen.main.bounds.size.width * 0.2, height: UIScreen.main.bounds.size.width * 0.6))
let rightView = UIView(frame: CGRect(x: UIScreen.main.bounds.size.width * 0.8, y: UIScreen.main.bounds.size.height * 0.35, width: UIScreen.main.bounds.size.width * 0.2, height: UIScreen.main.bounds.size.width * 0.6))
let bottomView = UIView(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.width * 0.6 + UIScreen.main.bounds.size.height * 0.35, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height * 0.65 - UIScreen.main.bounds.size.width * 0.6))
topView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
bottomView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
leftView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
rightView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
// 文字说明
let label = UILabel(frame: CGRect(x: 0, y: 10, width: UIScreen.main.bounds.size.width, height: 21))
label.textAlignment = NSTextAlignment.center
label.font = UIFont.systemFont(ofSize: 14)
label.textColor = UIColor.white
label.text = "将二维码/条形码放入扫描框内,即自动扫描"
bottomView.addSubview(label)
self.bgView.addSubview(topView)
self.bgView.addSubview(bottomView)
self.bgView.addSubview(leftView)
self.bgView.addSubview(rightView)
// 屏幕中间扫描区域视图(透明)
barcodeView.frame = CGRect(x: UIScreen.main.bounds.size.width * 0.2, y: UIScreen.main.bounds.size.height * 0.35, width: UIScreen.main.bounds.size.width * 0.6, height: UIScreen.main.bounds.size.width * 0.6)
barcodeView.backgroundColor = UIColor.clear
barcodeView.layer.borderWidth = 1.0
barcodeView.layer.borderColor = UIColor.white.cgColor
self.bgView.addSubview(barcodeView)
// 扫描线
scanLine.frame = CGRect(x: 0, y: 0, width: barcodeView.frame.size.width, height: 5)
scanLine.image = UIImage(named: "QRCodeScanLine")
barcodeView.addSubview(scanLine)
}
// 扫描线滚动
func moveScannerLayer(_ timer : Timer) {
self.scanLine.frame = CGRect(x: 0, y: 0, width: self.barcodeView.frame.size.width, height: 12)
UIView.animate(withDuration: 2) {
self.scanLine.frame = CGRect(x: self.scanLine.frame.origin.x, y: self.scanLine.frame.origin.y + self.barcodeView.frame.size.height - 10, width: self.scanLine.frame.size.width, height: self.scanLine.frame.size.height)
}
}
}
|
//
// MainController.swift
// HNMobileTest
//
// Created by Oscar Cuadra on 1/26/18.
// Copyright © 2018 Oscar Cuadra. All rights reserved.
//
import UIKit
import RealmSwift
class MainController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var rowTapped = 0
//The key to refresh our tableView
var refreshControl: UIRefreshControl = UIRefreshControl()
//Realm parameters
var hitsList : Results<Hit>!
var notificationToken : NotificationToken?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = true
self.tableView.dataSource = self
self.tableView.delegate = self
self.refreshControl.addTarget(self, action: #selector(MainController.refreshData), for: UIControlEvents.valueChanged)
addRefreshControl()
loadDataBase()
let nibRow = UINib(nibName: "CustomCell", bundle: nil)
self.tableView.register(nibRow, forCellReuseIdentifier: "customCell")
}
private func loadDataBase() {
//Configuracion Realm
let realm = RealmService.shared.realm
APIClient().loadJSONData()
// ealmResults<MyTable> list = realm.where(MyTable.class)
// .sort("date",Sort.DESCENDING)
// .findAll();
//// self.hitsList = realm.objects(Hit.self)
self.hitsList = realm.objects(Hit.self).sorted(byKeyPath: "created_at", ascending: false)
self.notificationToken = realm.observe({(notification, realm) in
self.tableView.reloadData()
})
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = true
}
//This method add our refresh function
private func addRefreshControl() {
//We control if the device has ios 10 or less
if #available(iOS 10.0, *) {
self.tableView.refreshControl = self.refreshControl
} else {
self.tableView.addSubview(self.refreshControl)
}
}
@objc func refreshData() {
self.loadDataBase()
// self.tableView.reloadData
self.refreshControl.endRefreshing()
}
// func orderAscendingDates() {
// let formatter = DateFormatter()
// formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
// var elapsed: Double!
//
// for hit in self.hitsList {
// if let date = formatter.date(from:"2018-01-12T00:00:00.000Z") {
//
// }
// }
//
//
//
// dateFormatter.dateFormat = "dd MM, yyyy"// yyyy-MM-dd"
//
// for hit in self.hitsList {
// let date = dateFormatter.date(from: hit.)
// if let date = date {
// convertedArray.append(date)
// }
// }
//
// var ready = convertedArray.sorted(by: { $0.compare($1) == .orderedDescending })
}
extension MainController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return hitsList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomCell
let item = hitsList[indexPath.row]
// create NSDate from Double (NSTimeInterval)
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
if let date = formatter.date(from: item.created_at!) {
let elapsed = TimeObserver.timeAgoSinceDate(date: date as NSDate, numericDates: false)
let authorLabel = "\(item.author ?? "none") - \(elapsed)"
cell.customInit(story_title: item.story_title ?? "", author: authorLabel)
} else {
cell.customInit(story_title: item.story_title ?? "", author: item.author ?? "")
}
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == UITableViewCellEditingStyle.delete) {
if (hitsList?[indexPath.row]) != nil {
RealmService.shared.deleteObject(hitsList[indexPath.row])
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.rowTapped = indexPath.row
performSegue(withIdentifier: "showDetail", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? WebViewController {
destination.hits = hitsList[rowTapped]
}
}
}
|
//
// showTeamsViewController.swift
// game
//
// Created by Fredrik Carlsson on 2018-01-16.
// Copyright © 2018 Fredrik Carlsson. All rights reserved.
//
import UIKit
class showTeamsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var i = 1
@IBOutlet weak var playerTableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let team = teamID{
return LocalDataBase.teamArray[team].players.count
}
else{
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "basicCell")
if let team = teamID{
cell.textLabel?.text = LocalDataBase.teamArray[team].players[indexPath.row].name
}
let clearView = UIView()
clearView.backgroundColor = UIColor.clear
UITableViewCell.appearance().selectedBackgroundView = clearView
cell.textLabel?.textAlignment = .center
cell.backgroundColor = .clear
cell.tintColor = .black
return cell
}
var teamID: Int?
@IBOutlet weak var teamLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var teamNameTextView: UITextFieldX!
@IBOutlet weak var scoreTextView: UITextFieldX!
@IBOutlet weak var editButtonOutlet: UIButton!
var data = [Player]()
var player: Player?
var filePath: String {
let manager = FileManager.default
let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
return url!.appendingPathComponent("Data").path
}
private func loadData(){
if let ourData = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? [Player]{
data = ourData
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
for player in data{
if let team = teamID{
if(LocalDataBase.teamArray[team].players[indexPath.row].name == player.name){
self.player = player
performSegue(withIdentifier: "teamToPlayerSegue", sender: self)
}
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? PlayerViewController{
if let selectedPlayer = player{
destination.player = selectedPlayer
}
}
}
@IBAction func editTeamButton(_ sender: UIButton) {
if(editButtonOutlet.title(for: .normal) == NSLocalizedString("edit", comment: "")){
editButtonOutlet.setTitle(NSLocalizedString("done", comment: ""), for: .normal)
teamNameTextView.isHidden = false
scoreTextView.isHidden = false
}
else if(editButtonOutlet.title(for: .normal) == NSLocalizedString("done", comment: "")){
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(AddPlayerViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
if let team = teamID{
if(teamNameTextView.text != ""){
LocalDataBase.teamArray[team].name = teamNameTextView.text!
teamLabel.text = teamNameTextView.text
}
if(scoreTextView.text != ""){
let newScore = processData(data: Int(scoreTextView.text!))
LocalDataBase.teamArray[team].points = newScore
scoreLabel.text = "\(newScore ) " + NSLocalizedString("points", comment: "")
}
}
teamNameTextView.isHidden = true
scoreTextView.isHidden = true
editButtonOutlet.setTitle(NSLocalizedString("edit", comment: ""), for: .normal)
}
}
func processData(data: Int?) -> Int {
guard let result = data else {
return LocalDataBase.teamArray[teamID!].points
}
return result
}
override func viewDidLoad() {
super.viewDidLoad()
loadData()
if let index = teamID {
teamLabel.text = String(LocalDataBase.teamArray[index].name)
scoreLabel.text = "\(LocalDataBase.teamArray[index].points) " + NSLocalizedString("points", comment: "")
teamNameTextView.placeholder = String(LocalDataBase.teamArray[index].name)
scoreTextView.placeholder =
String(LocalDataBase.teamArray[index].points)
}
}
@objc func dismissKeyboard(){
view.endEditing(true)
}
@IBAction func closeButton(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func doneButton(_ sender: UIButton) {
if let team = teamID{
if let textView = teamNameTextView.text{
if(textView != ""){
LocalDataBase.teamArray[team].name = textView
}
}
if let points = scoreTextView.text {
if(points != ""){
LocalDataBase.teamArray[team].points = Int(points)!
}
}
}
self.dismiss(animated: true, completion: nil)
}
@IBAction func dismissBackground(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
|
//
// MyPlaceEditViewController.swift
// YuluDemo
//
// Created by Admin on 10/21/19.
// Copyright © 2019 Admin. All rights reserved.
//
import UIKit
class MyPlaceEditViewController: UIViewController,StoryboardIdentifiable {
@IBOutlet weak var TitleTextField: UITextField!
@IBOutlet weak var subTitleTextField: UITextView!
@IBOutlet weak var CoordinatorButton: UIButton!
private var viewModel:MyPlaceEditViewModel! // ViewModel
override func viewDidLoad() {
super.viewDidLoad()
setUpViewModel()
// Do any additional setup after loading the view.
}
class func controller(viewModel: MyPlaceEditViewModel) -> MyPlaceEditViewController {
let vc:MyPlaceEditViewController = UIStoryboard (storyboard: .main).instantiateViewController()
vc.viewModel = viewModel
return vc
}
private func setUpViewModel() {
viewModel.showAlert = { [weak self](message) in
if let result = message {
self?.showAlert(message: result)
}
}
}
override func viewWillAppear(_ animated: Bool) {
self.TitleTextField.text = self.viewModel.getTitle()
self.subTitleTextField.text = self.viewModel.getDescription()
self.CoordinatorButton.setTitle(self.viewModel.getCoordinate(), for: .normal)
}
@IBAction func updateCoordinateAction(_ sender: Any) {
//self.showAlert()
self.viewModel.mapViewLoad()
}
@IBAction func SaveEditMyplace(_ sender: Any) {
self.viewModel.updateTitle(title: TitleTextField.text!)
self.viewModel.updateMyPlace()
}
// func showAlert(message: String){
//
// let alert = UIAlertController(title: "Result", message: message, preferredStyle: .alert)
//
// alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in
//
// if message != "Fail" {
// self.navigationController?.popViewController(animated: true)
// }
//
// }))
//
// self.present(alert, animated: true, completion: nil)
//
// }
}
|
//
// BaseReq.swift
// MsdGateLock
//
// Created by xiaoxiao on 2017/5/25.
// Copyright © 2017年 xiaoxiao. All rights reserved.
//
import Foundation
import ObjectMapper
typealias CommonReq = BaseReq<EmptyParam>
class BaseReq<T :Mappable> :Mappable
{
init(){}
var id:Int = 1
var sessionId:String = ""
var action:String = ""
var sign:String = ""
var data:T?
required
init?(map: Map) {
}
func mapping(map: Map) {
id <- map["id"]
sessionId <- map["sessionId"]
action <- map["action"]
sign <- map["sign"]
data <- map["data"]
// regTime <- (map["regTime"], GameDateTransform())
}
}
class BaseArrReq<T :Mappable> :Mappable
{
init(){}
var id:Int = 1
var sessionId:String = ""
var action:String = ""
var sign:String = ""
var data:[T]?
required
init?(map: Map) {
}
func mapping(map: Map) {
id <- map["id"]
sessionId <- map["sessionId"]
action <- map["action"]
sign <- map["sign"]
data <- map["data"]
// regTime <- (map["regTime"], GameDateTransform())
}
}
|
//
// MissionFooterTableViewCell.swift
// strolling-of-time-ios
//
// Created by 강수진 on 2019/08/17.
// Copyright © 2019 wiw. All rights reserved.
//
import UIKit
class MissionFooterTableViewCell: UITableViewCell, NibLoadable {
@IBOutlet weak var pastMissionButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
|
../../../StellarKit/source/types/PublicKey.swift |
//
// MKMultiPointExtension.swift
// googleMapz
//
// Created by Macbook on 6/19/21.
//
import Foundation
import MapKit
public extension MKMultiPoint {
var coordinates: [CLLocationCoordinate2D] {
var coords = [CLLocationCoordinate2D](repeating: kCLLocationCoordinate2DInvalid,
count: pointCount)
getCoordinates(&coords, range: NSRange(location: 0, length: pointCount))
return coords
}
}
|
//
// ViewController.swift
// grubber
//
// Created by JABE on 11/12/15.
// Copyright © 2015 JABELabs. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController, PFLogInViewControllerDelegate {
@IBOutlet var appLabel: UILabel!
@IBOutlet var retryButton: UIButton!
var activityIndicator : JLActivityIndicator!
var netChecker = Factory.createNetConnectivityChecker()
var fbAdapter = Factory.createFBAdapter()
override func viewDidLoad() {
super.viewDidLoad()
UIFactory.configureAppLabel(appLabel)
retryButton.hidden = true
activityIndicator = JLActivityIndicator(parentView: self.view, onTopOfView: self.view, startAnimating: true, drawOverlayOverParentView: false)
doLogin()
}
func checkNetConnectivity() -> Bool {
if !netChecker.isNetworkAvailable() {
activityIndicator.stopAnimation()
ThreadingUtil.inBackgroundAfter({ () -> Void in
Util.showMessage(self, msg: UserMessage.NoInternet.rawValue, title: "", completionBlock: nil)
}, afterDelay: 0.3)
retryButton.hidden = false
return false
}
return true
}
@IBAction func retryButtonPressed(sender: AnyObject) {
onRetry()
}
func onRetry(){
retryButton.enabled = false
activityIndicator.startAnimation()
doLogin()
retryButton.enabled = true
activityIndicator.stopAnimation()
}
@IBAction func logout(segue: UIStoryboardSegue){
PFUser.logOut()
onRetry()
}
func doLogin() {
if !checkNetConnectivity() {
return
}
var isAuthenticated = false
ThreadingUtil.inBackground({
isAuthenticated = PFUser.currentUser() != nil
}) {
if isAuthenticated {
self.retryButton.enabled = false
self.onPostAuthentication()
} else {
let loginViewController = AppPFLoginViewController()
loginViewController.delegate = self
// loginViewController.fields = .UsernameAndPassword | .LogInButton | .PasswordForgotten | .SignUpButton | .Facebook | .Twitter
loginViewController.facebookPermissions = [FBPermission.friends.rawValue]
loginViewController.fields = [ .UsernameAndPassword, .LogInButton, .PasswordForgotten, .SignUpButton, .Facebook]
loginViewController.emailAsUsername = true
loginViewController.signUpController = AppPFSignupViewController()
loginViewController.signUpController?.emailAsUsername = true
// loginViewController.signUpController?.delegate = self
self.presentViewController(loginViewController, animated: false, completion: nil)
}
}
}
func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) {
self.dismissViewControllerAnimated(true, completion: nil)
ThreadingUtil.inBackgroundAfter({ () -> Void in
self.onPostAuthentication()
}, afterDelay: 0.3)
}
func onPostAuthentication() {
if fbAdapter.isUserLoggedThruFacebook(){
let currentPfUser = PFUser.currentUser()!
if let fbId = currentPfUser.objectForKey(AppUserFields.fbId.rawValue) as? String {
if fbId.isEmpty {
self.saveFbDataAndSegueToHome()
}
else {
self.segueToHome()
}
} else {
self.saveFbDataAndSegueToHome()
}
} else {
self.segueToHome()
}
}
func saveFbDataAndSegueToHome(){
guard let currentPfUser = PFUser.currentUser() else {
return
}
self.fbAdapter.getFbUserData(false, completion: { (userData, error) -> Void in
if error == nil {
if let fbData = userData {
currentPfUser.setObject(fbData.fbId, forKey: AppUserFields.fbId.rawValue)
currentPfUser.setObject(fbData.firstName, forKey: AppUserFields.fbFirstName.rawValue)
currentPfUser.setObject(fbData.lastName, forKey: AppUserFields.fbLastName.rawValue)
currentPfUser.saveInBackgroundWithBlock({ (success, error) -> Void in
if error != nil {
print("Failed to save FbId: \(error)")
} else {
self.segueToHome()
}
})
}
} else {
print("Failed to retrieve and save FbId: \(error)")
}
})
}
func segueToHome() {
if Restaurant.doesUserHaveRestaurant() {
ThreadingUtil.inBackgroundAfter({ () -> Void in
self.performSegueWithIdentifier("segueToHome", sender: nil)
}, afterDelay: 0.3)
}
else {
UIFactory.createWelcomeScreenController(self)
}
}
}
|
//
// HomeViewController.swift
// SalemanChecking
//
// Created by hieu nguyen van on 9/7/19.
// Copyright © 2019 hieunv. All rights reserved.
//
import UIKit
import CoreLocation
struct TimeChecking: Decodable{
let success: Bool
let valid: Bool
let distance: Float!
let updated_date: String!
let msg: String!
enum CodingKeys: String, CodingKey {
case success = "success"
case valid = "valid"
case distance = "distance"
case updated_date = "updated_date"
case msg = "msg"
}
}
class HomeViewController: UIViewController, CLLocationManagerDelegate {
var fullname: String!
var usr_id: String!
var access_token: String!
var app_token: String!
var usr_icon: String!
var curr_long: String!
var curr_lat: String!
var locationManager = CLLocationManager()
@IBOutlet weak var myIconView: UIImageView!
@IBOutlet weak var myNavigationItem: UINavigationItem!
@IBOutlet weak var myNavigationBar: UINavigationBar!
override func viewDidLoad() {
super.viewDidLoad()
//UserDefaults.standard.set(usr_icon, forKey: "Usr_icon")
//print(usr_icon!)
//let leftName = UIButton(type: .system)
//leftName.setTitle("Xin chào \(fullname!)", for: .normal)
//myNavigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftName)
//right bar button
//myNavigationItem.rightBarButtonItem = UIBarButtonItem(title: "Thoát", style: .plain, target: self, action: #selector(btnSignout))
//set icon của
//let image: UIImage = UIImage(named: "titleimg")!
//let titleImage = UIImageView(image: image)
//titleImage.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
//titleImage.contentMode = .scaleAspectFit
//myNavigationItem.titleView = titleImage
self.view.addBackground()
myNavigationItem.title = "Xin chào \(fullname!)"
let myicon: UIImage = UIImage(named: "titleimg")!
myIconView.image = myicon
self.navigationItem.setHidesBackButton(true, animated: false)
}
@IBAction func btnSignout(_ sender: Any) {
UserDefaults.standard.set(false, forKey: "isLogedin")
UserDefaults.standard.set(fullname, forKey: "udf_name")// trả ra màn hình login
UserDefaults.standard.set(usr_icon, forKey: "Usr_icon")
let siginView = self.storyboard?.instantiateViewController(withIdentifier: "SigninViewController") as! ViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = siginView
}
/*
@objc func btnSignout() {
UserDefaults.standard.set(false, forKey: "isLogedin")
UserDefaults.standard.set(fullname, forKey: "udf_name")// trả ra màn hình login
UserDefaults.standard.set(usr_icon, forKey: "Usr_icon")
let siginView = self.storyboard?.instantiateViewController(withIdentifier: "SigninViewController") as! ViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = siginView
}
*/
@IBAction func btnTest(_ sender: Any) {
//Get current location
if (CLLocationManager.locationServicesEnabled())
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
let location: CLLocationCoordinate2D = locationManager.location!.coordinate
//print("mobile locations = \(location.latitude) \(location.longitude)")
curr_lat = String(location.latitude)
curr_long = String(location.longitude)
}
var mylink = UserDefaults.standard.object(forKey: "Link") as! String
mylink += "api/timekeeping_checkin"
//print(mylink)
let myUrl = URL(string: mylink)
var request = URLRequest(url: myUrl!)
request.httpMethod = "POST"
//app_token và access_token được gửi về từ ViewDidLoad của ViewController.swift
let postString = "&access_token=\(access_token!)&app_token=\(app_token!)&usr_long=\( curr_long!)&usr_lat=\(curr_lat!)"
//print(postString)
let postData = postString.data(using: .utf8) // convert to utf8 string
request.httpBody = postData
do
{
let uploadJob = URLSession.shared.uploadTask(with: request, from: postData){responseData, response, error in
if error != nil {
DispatchQueue.main.async
{
displayMessage(message: "Looks like the connection to the server didn't work. Do you have Internet access?", title: "Alert", vw: self)
}
}else
{
do{
let jsonresData = try JSONDecoder().decode(TimeChecking.self, from: responseData!)
if (jsonresData.valid)
{
displayMessage(message: jsonresData.msg + " Khoảng cách sai số: " + String(jsonresData.distance), title: "Alert", vw: self)
}
else
{
DispatchQueue.main.async
{
displayMessage(message: jsonresData.msg, title: "Alert", vw: self)
}
}
} catch{
displayMessage(message: error as! String, title: "Alert", vw: self)
}
}
}
uploadJob.resume()
}
}
}
|
//
// Employee.swift
// CompanyDirectory
//
// Created by 大林拓実 on 2021/02/17.
//
import Foundation
struct Employee: Codable {
/* ここから */
var id = UUID()
var name: String
var isOnline: Bool
var contactAddress: String
var teamID: UUID?
/* ここまで */
var teamName: String {
let database = Database()
guard let teamID = self.teamID else { return "なし" }
let team = database.teams.first(where: { $0.id == teamID })
return team?.name ?? "なし"
}
func save() {
let database = Database()
database.setEmployeeData(self)
}
func delete() {
let database = Database()
do {
try database.deleteEmployeeData(self)
} catch let error {
print(error.localizedDescription)
}
}
mutating func joinTeam(by name: String) {
let database = Database()
let team = database.teams.filter { $0.name == name }.first
self.teamID = team?.id
save()
}
mutating func leaveTeam() {
self.teamID = nil
save()
}
}
|
//
// PostTableViewCell.swift
// LocalReads
//
// Created by Tom Seymour on 2/18/17.
// Copyright © 2017 C4Q-3.2. All rights reserved.
//
import UIKit
import Cosmos
class PostTableViewCell: UITableViewCell {
@IBOutlet weak var cardView: UIView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var bookCoverImageView: UIImageView!
@IBOutlet weak var userProfileImageView: UIImageView!
@IBOutlet weak var bookTitileLabel: UILabel!
@IBOutlet weak var bookAuthorLabel: UILabel!
@IBOutlet weak var libraryNameLabel: UILabel!
@IBOutlet weak var userRatingLabel: UILabel!
@IBOutlet weak var userCommentLabel: UILabel!
@IBOutlet weak var bookCoverTopConstraint: NSLayoutConstraint!
@IBOutlet weak var coverLoadActivityIndicator: UIActivityIndicatorView!
override func awakeFromNib() {
super.awakeFromNib()
userProfileImageView.layer.cornerRadius = 22
userProfileImageView.clipsToBounds = true
cardView.layer.shadowColor = UIColor.black.cgColor
cardView.layer.shadowOpacity = 0.8
cardView.layer.shadowOffset = CGSize(width: 0, height: 5)
cardView.layer.shadowRadius = 8
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func rating(_ value: Int) {
var ratingString = ""
for _ in 1...value {
ratingString += "⭐"
}
self.userRatingLabel.text = ratingString
}
}
|
import Foundation
// MARK: - ℹ️ Инструкция
//
// Чтобы выполнить практическое задание, вам потребуется:
// 1. Прочитайте условие задания
// 2. Напишите ваше решение ниже в этом файле в разделе "Решение".
// 3. После того как решение будет готово, запустите Playground,
// чтобы проверить свое решение тестами
// MARK: - ℹ️ Условие задания
//
// 1. Создайте переменную `age` и сохраните в нее промежуток от 1 до 100, включая 100
// 2. Создайте переменную `price` и сохраните в нее промежуток от 100 до 1000, не включая 1000
// 3. Создайте переменную `maxProducts` и сохраните в нее промежуток до 10, не включая 10
//
// MARK: - 🧑💻 Решение
// --- НАЧАЛО КОДА С РЕШЕНИЕМ ---
var age = 1...100
var price = 100..<1000
var maxProducts = ..<10
// --- КОНЕЦ КОДА С РЕШЕНИЕМ ---
// MARK: - 🛠 Тесты
// - Здесь содержится код запуска тестов для вашего решения
// - ⚠️ Не меняйте этот код
TestRunner.runTests(.default(age, price, maxProducts))
|
import UIKit
/// Конформить этот протокол, когда ячейка грузится не из xib'a.
public protocol Reusable: class {
static var reuseIdentifier: String { get }
}
/// Конформить этот протокол, когда ячейка грузится из xib.
public typealias NibReusable = Reusable & NibLoadable
public extension Reusable {
/// По умолчанию используем имя класса в качестве идентификатора ячейки
static var reuseIdentifier: String {
return String(describing: self)
}
}
|
import UIKit
import Cartography
class ReviewViewController: FormViewController {
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var categoryTextField: UITextField!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var photoView: UIImageView!
@IBOutlet var formView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "REVIEW"
var descFlag = false
setupCategoryFields()
setupLocationFields()
setupDescriptionFields()
setupImageFields()
constrain(categoryLabel) { categoryLabel in
categoryLabel.width == categoryLabel.superview!.width * 0.8
}
self.formView.backgroundColor = UIColor(white: 1.0, alpha: 0.3)
addNextButton("SEND REPORT", segueIdentifier: "ThankYouSegue")
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "preferredContentSizeChanged:",
name: UIContentSizeCategoryDidChangeNotification,
object: nil)
}
func preferredContentSizeChanged(notification: NSNotification) {
for label in [locationLabel, categoryLabel, descriptionLabel] {
label.font = Font.preferredFontForTextStyle(UIFontTextStyleBody)
label.setHeadingFontSmall()
}
for field in [locationTextField, categoryTextField, descriptionTextView] {
if let textField = field as? UITextField {
textField.font = Font.preferredFontForTextStyle(UIFontTextStyleBody)
textField.setBodyFontSmall()
} else if let textView = field as? UITextView {
textView.font = Font.preferredFontForTextStyle(UIFontTextStyleBody)
textView.setBodyFontSmall()
}
}
}
func setupCategoryFields(){
categoryLabel.setHeadingFontSmall()
categoryLabel.text! = categoryLabel.text!.uppercaseString
categoryTextField.setBodyFontSmall()
if let categoryName = Report.getCurrentReport().category?.name {
categoryTextField.text = categoryName
}
}
func setupLocationFields(){
locationLabel.setHeadingFontSmall()
locationLabel.text! = locationLabel.text!.uppercaseString
locationTextField.setBodyFontSmall()
descriptionTextView.setBodyFontSmall()
descriptionLabel.setHeadingFontSmall()
descriptionLabel.text! = descriptionLabel.text!.uppercaseString
descriptionLabel.layer.borderWidth = 0.0 // no border
if let locationDescription = Report.getCurrentReport().location?.desc {
locationTextField.text = locationDescription
}
}
func setupDescriptionFields(){
descriptionTextView.setBodyFontSmall()
descriptionLabel.setHeadingFontSmall()
if let description = Report.getCurrentReport().description {
descriptionLabel.hidden = false
descriptionTextView.hidden = false
descriptionTextView.text = description
} else {
descriptionLabel.hidden = true
descriptionTextView.hidden = true
}
}
func setupImageFields(){
if let image = Report.getCurrentReport().image {
photoView.image = UIImage(data:image)
photoView.contentMode = UIViewContentMode.ScaleAspectFit
if descriptionTextView.hidden {
constrain(photoView, categoryTextField) { photoView, categoryTextField in
photoView.top == categoryTextField.bottom+20
}
} else{
}
} else {
photoView.hidden = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func performSegueWithIdentifier(identifier: String?, sender: AnyObject?) {
let isRegistered = UserTokenMgr.sharedInstance.hasToken()
if(isRegistered) {
Report.getCurrentReport().userUUID = UserTokenMgr.sharedInstance.token()!
}
var segueIdentifier = isRegistered ? "ThankYouSegue" : "SignUpSegue"
super.performSegueWithIdentifier(segueIdentifier, sender: nil)
}
} |
//
// Token.swift
// WarriorLangSwiftCompiler
//
// Created by Rafael Guerreiro on 2018-09-27.
// Copyright © 2018 Rafael Rubem Rossi Souza Guerreiro. All rights reserved.
//
import Foundation
public class Token {
public let category: TokenCategory
public let value: String
public let file: String
public let range: TokenRange
init(category: TokenCategory,
value: String,
file: String,
range: TokenRange)
{
self.category = category
self.value = value
self.file = file
self.range = range
}
public func isCategory(_ category: TokenCategory) -> Bool {
return self.category == category
}
}
extension Token: CustomStringConvertible {
public var description: String {
return "\(category): \(range) => '\(value)'";
}
}
public class NumberLiteralToken: Token {
public let radix: UInt8 // 2, 8, 10, 16
public let isFloatingPoint: Bool // [digit]\.[digit]
init(token: Token, radix: UInt8, isFloatingPoint: Bool) {
self.radix = radix
self.isFloatingPoint = isFloatingPoint
super.init(category: token.category,
value: token.value,
file: token.file,
range: token.range)
}
}
class TokenBuilder: CustomStringConvertible {
let file: String
private(set) var value: String = ""
private(set) var range: TokenRange
private(set) var radix: UInt8?
private var floatingPoint: Bool?
init(file: String) {
self.file = file
self.range = TokenRange(file: file)
}
func reset() {
self.value = ""
self.range = TokenRange(file: file, index: range.endIndex, line: range.endLine, column: range.endColumn)
self.radix = nil
self.floatingPoint = nil
}
func increment(char: String) {
self.value += char
self.range.increment(char: char)
}
func radix(_ radix: UInt8) {
self.radix = radix
}
var isFloatingPoint: Bool {
return self.floatingPoint ?? false
}
func isFloatingPoint(_ floatingPoint: Bool) {
self.floatingPoint = floatingPoint
}
func build(category: TokenCategory) -> Token {
let token = Token(category: category,
value: value,
file: file,
range: range)
if let radix = self.radix,
let floatingPoint = self.floatingPoint
{
return NumberLiteralToken(token: token, radix: radix, isFloatingPoint: floatingPoint)
}
return token
}
var description: String {
return "file: \(file), value: \"\(value)\", range: \(range), radix: \(String(describing: radix)), isFloatingPoint: \(String(describing: floatingPoint))"
}
}
|
//
// customTableViewCell.swift
// GithubDemo
//
// Created by Dwayne Johnson on 2/16/17.
// Copyright © 2017 codepath. All rights reserved.
//
import UIKit
class customTableViewCell: UITableViewCell {
@IBOutlet weak var repoName: UILabel!
@IBOutlet weak var ownerHandle: UILabel!
@IBOutlet weak var ownerAvatar: UIImageView!
@IBOutlet weak var starsLabel: UILabel!
@IBOutlet weak var forksLabel: UILabel!
@IBOutlet weak var repoDescription: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// PriceItemCell.swift
// MyLoqta
//
// Created by Ashish Chauhan on 16/08/18.
// Copyright © 2018 AppVenturez. All rights reserved.
//
import UIKit
class PriceItemCell: BaseTableViewCell, NibLoadableView, ReusableView {
@IBOutlet weak var imgViewProduct: UIImageView!
@IBOutlet weak var lblPrice: UILabel!
@IBOutlet weak var lblItemName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configureCell(product: Product) {
if let imageUrl = product.imageFirstUrl {
self.imgViewProduct.setImage(urlStr: imageUrl, placeHolderImage: UIImage())
self.imgViewProduct.roundCorners(4)
} else if let array = product.imageUrl, array.count > 0 {
let imageUrl = array[0]
self.imgViewProduct.setImage(urlStr: imageUrl, placeHolderImage: UIImage())
self.imgViewProduct.roundCorners(4)
}
if let name = product.itemName {
self.lblItemName.text = name
}
if let price = product.price {
let intPrice = Int(price)
let usPrice = intPrice.withCommas()
self.lblPrice.text = usPrice
}
}
}
|
//
// PersonalDetailVC.swift
// LetsPo
//
// Created by 溫芷榆 on 2017/7/23.
// Copyright © 2017年 Walker. All rights reserved.
//
import UIKit
class PersonalDetailVC: UIViewController ,UITableViewDelegate, UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
@IBOutlet weak var personalImage: UIImageView!
@IBOutlet weak var selfDataTable: UITableView!
@IBOutlet weak var nameLabel: UILabel!
let cellTitle = ["ID:","Name:","E-Mail:"]
let cellSubtitle = ["9527","PinLiao","nioh946@gmail.com"]
let selfieBgImageNN = Notification.Name("selfie")
var photographer = UIImagePickerController()
var imageFactory = MyPhoto()
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.text = cellSubtitle[1]
setLabelWithFrame()
personalImage.backgroundColor = UIColor.black
personalImage.layer.cornerRadius = personalImage.frame.size.width / 2
personalImage.layer.masksToBounds = true
// personalImage.frame = CGRect(x: self.view.center.x - 75, y: 75, width: 150, height: 150)
}
@IBAction func editeSelfie(_ sender: Any) {
let alert = UIAlertController(title: "Edite", message: "Please select source", preferredStyle:.alert)
let camera = UIAlertAction(title: "Camera", style: .default) { _ in
self.photographer.sourceType = .camera
self.photographer.cameraDevice = .rear
self.photographer.allowsEditing = true
self.photographer.delegate = self
self.present(self.photographer, animated: true, completion: nil)
}
let photos = UIAlertAction(title: "Photos", style: .default) { _ in
self.photographer.sourceType = .photoLibrary
self.photographer.allowsEditing = true
self.photographer.delegate = self
self.present(self.photographer, animated: true, completion: nil)
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(camera)
alert.addAction(photos)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellTitle.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
cell?.textLabel?.text = cellTitle[indexPath.row]
cell?.detailTextLabel?.text = cellSubtitle[indexPath.row]
cell?.frame = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 30)
cell?.selectionStyle = .default
return cell!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setLabelWithFrame(){
nameLabel.font = UIFont.systemFont(ofSize: 25)
nameLabel.frame = CGRect(x: 0, y: self.view.center.y * 0.70, width: UIScreen.main.bounds.size.width, height: 30)
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = false
self.navigationController?.navigationBar.barTintColor = UIColor.white
self.navigationItem.title = "個人資料"
// self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(editBtnAction))
}
func saveImage(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
// we got back an error!
let saveAlert = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
saveAlert.addAction(UIAlertAction(title: "OK", style: .default))
present(saveAlert, animated: true)
} else {
let saveAlert = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
saveAlert.addAction(UIAlertAction(title: "OK", style: .default))
present(saveAlert, animated: true)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage
else{
return
}
//resize image
guard let imageX = imageFactory.resizeFromImage(input: image)
else {
return
}
UIImageWriteToSavedPhotosAlbum(imageX, self, #selector(saveImage(_:didFinishSavingWithError:contextInfo:)), nil)
NotificationCenter.default.post(name: selfieBgImageNN, object: nil, userInfo: ["selfieBg":imageX])
//Change selfie image
personalImage.image = imageX
self.dismiss(animated: true, completion: nil)
}
}
// func editBtnAction(){
// let nextPage = storyboard?.instantiateViewController(withIdentifier: "InfoEditVC") as? InfoEditVC
// nextPage?.navigationItem.leftItemsSupplementBackButton = true
// navigationController?.pushViewController(nextPage!, animated: true)
// }
//
|
//
// Palette.swift
// WeatherApp
//
// Created by Dzhek on 14.09.2020.
// Copyright © 2020 Dzhek. All rights reserved.
//
import struct SwiftUI.Color
import struct SwiftUI.Gradient
enum Palette {
static let primary = Color("primary")
static let secondary = Color("secondary")
static let tertiary = Color("tertiary")
static let сobaltBlue = Color("сobaltBlue")
static let mayaBlue = Color("mayaBlue")
static let capri = Color("capri")
static let transparentSystemGray6 = Color(.systemGray6).opacity(0.5)
static let coolSkyGradient = Gradient(colors: [сobaltBlue.opacity(0.9),
mayaBlue.opacity(0.6),
capri.opacity(0.3),
capri.opacity(0)])
static let arcGradient = Gradient(colors: [capri.opacity(0.2),
capri.opacity(0.5),
mayaBlue.opacity(0.5),
mayaBlue.opacity(0.2)])
}
|
import Foundation
extension String {
subscript(index: Int) -> Character {
let sIndex = self.index(self.startIndex, offsetBy: index)
return self[sIndex]
}
}
extension Character {
var isDigit: Bool {
return "0"..."9" ~= self
}
}
func parse(_ pattern: String) -> [(character: Character, trailing: Int)] {
var items = [(character: Character, trailing: Int)]()
var i = 0
while i < pattern.count {
let character = pattern[i]
var count = 0
i += 1
while i < pattern.count && pattern[i].isDigit {
count = count * 10 + Int(String(pattern[i]))!
i += 1
}
items.append((character, count))
}
return items
}
func match(text: String, pattern: String) -> Bool {
let patternItems = parse(pattern)
var index = 0
for pItem in patternItems {
if index >= text.count && text[index] != pItem.character {
return false
}
index += 1
index += pItem.trailing
}
return index == text.count
}
let res = match(text: "facebook", pattern: "f6k")
print(res) |
import FluentMySQL
import Vapor
/// A single entry of a File list.
final class File: MySQLModel {
/// The unique identifier for this `File`.
var id: Int?
var name: String
var path: String
var owner: Int
/// Creates a new `File`.
init(id: Int? = nil, name: String, path: String, owner: Int) {
self.id = id
self.name = name
self.path = path
self.owner = owner
}
}
/// Allows `File` to be used as a dynamic migration.
extension File: Migration { }
/// Allows `File` to be encoded to and decoded from HTTP messages.
extension File: Content { }
/// Allows `File` to be used as a dynamic parameter in route definitions.
extension File: Parameter { } |
import Foundation
/// An object representing a single API operation on a path.
/// Get more info: https://swagger.io/specification/#operationObject
public struct SpecPathOperation: Codable, Equatable, Changeable {
// MARK: - Nested Types
private enum CodingKeys: String, CodingKey {
case identifier = "operationId"
case summary
case description
case externalDocs
case isDeprecated = "deprecated"
case responses
case parameters
case requestBody
case callbacks
case security
case servers
case tags
}
// MARK: - Instance Properties
private var extensionsContainer: SpecExtensionsContainer
/// Unique string used to identify the operation.
/// The identifier must be unique among all operations described in the API. The identifier value is case-sensitive.
/// It is recommended to follow common programming naming conventions.
public var identifier: String?
/// A short summary of what the operation does.
public var summary: String?
/// A verbose explanation of the operation behavior.
/// [CommonMark syntax](http://spec.commonmark.org/) may be used for rich text representation.
public var description: String?
/// Additional external documentation for this schema.
public var externalDocs: SpecExternalDocs?
/// Specifies that the operation is deprecated and should be transitioned out of usage.
/// Default value is `false`.
public var isDeprecated: Bool?
/// A list of parameters that are applicable for this operation.
/// If a parameter is already defined at the path object,
/// the new definition will override it but can never remove it.
/// The list must not include duplicated parameters.
/// A unique parameter is defined by a combination of a name and location.
public var parameters: [SpecComponent<SpecParameter>]?
/// The request body applicable for this operation.
/// This property is only supported in HTTP methods
/// where the HTTP 1.1 specification [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1)
/// has explicitly defined semantics for request bodies.
/// In other cases where the HTTP spec is vague, requestBody shall be ignored.
public var requestBody: SpecComponent<SpecRequestBody>?
/// The list of possible responses as they are returned from executing this operation.
public var responses: [String: SpecComponent<SpecResponse>]
/// A map between an event name and its out-of band callbacks related to the parent operation.
public var callbacks: [String: SpecComponent<SpecCallbacks>]?
/// A list of tags for API documentation control.
/// Tags can be used for logical grouping of operations by resources or any other qualifier.
public var tags: [String]?
/// An alternative server array to service this operation.
/// If an alternative server object is specified at the path object or root level,
/// it will be overridden by this value.
public var servers: [SpecServer]?
/// A declaration of which security mechanisms can be used for this operation.
/// The list of values includes alternative security requirement objects that can be used.
/// Only one of the security requirement objects need to be satisfied to authorize a request.
/// This definition overrides any declared top-level security.
/// To remove a top-level security declaration, an empty array can be used.
public var security: [SpecSecurityRequirement]?
/// The extensions properties.
/// Keys will be prefixed by "x-" when encoding.
/// Values can be a primitive, an array or an object. Can have any valid JSON format value.
public var extensions: [String: Any] {
get { extensionsContainer.content }
set { extensionsContainer.content = newValue }
}
// MARK: - Initializers
/// Creates a new instance with the provided values.
public init(
identifier: String? = nil,
summary: String? = nil,
description: String? = nil,
externalDocs: SpecExternalDocs? = nil,
isDeprecated: Bool? = nil,
parameters: [SpecComponent<SpecParameter>]? = nil,
requestBody: SpecComponent<SpecRequestBody>? = nil,
responses: [String: SpecComponent<SpecResponse>],
callbacks: [String: SpecComponent<SpecCallbacks>]? = nil,
tags: [String]? = nil,
servers: [SpecServer]? = nil,
security: [SpecSecurityRequirement]? = nil,
extensions: [String: Any] = [:]
) {
self.extensionsContainer = SpecExtensionsContainer(content: extensions)
self.identifier = identifier
self.summary = summary
self.description = description
self.externalDocs = externalDocs
self.isDeprecated = isDeprecated
self.parameters = parameters
self.requestBody = requestBody
self.responses = responses
self.callbacks = callbacks
self.tags = tags
self.servers = servers
self.security = security
}
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
identifier = try container.decodeIfPresent(forKey: .identifier)
summary = try container.decodeIfPresent(forKey: .summary)
description = try container.decodeIfPresent(forKey: .description)
externalDocs = try container.decodeIfPresent(forKey: .externalDocs)
isDeprecated = try container.decodeIfPresent(forKey: .isDeprecated)
parameters = try container.decodeIfPresent(forKey: .parameters)
requestBody = try container.decodeIfPresent(forKey: .requestBody)
responses = try container.decode(forKey: .responses)
callbacks = try container.decodeIfPresent(forKey: .callbacks)
tags = try container.decodeIfPresent(forKey: .tags)
servers = try container.decodeIfPresent(forKey: .servers)
security = try container.decodeIfPresent(forKey: .security)
extensionsContainer = try SpecExtensionsContainer(from: decoder)
}
// MARK: - Instance Methods
/// Encodes this instance into the given encoder.
///
/// This function throws an error if any values are invalid for the given encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(identifier, forKey: .identifier)
try container.encodeIfPresent(summary, forKey: .summary)
try container.encodeIfPresent(description, forKey: .description)
try container.encodeIfPresent(externalDocs, forKey: .externalDocs)
try container.encodeIfPresent(isDeprecated, forKey: .isDeprecated)
try container.encodeIfPresent(parameters, forKey: .parameters)
try container.encodeIfPresent(requestBody, forKey: .requestBody)
try container.encode(responses, forKey: .responses)
try container.encodeIfPresent(callbacks, forKey: .callbacks)
try container.encodeIfPresent(tags, forKey: .tags)
try container.encodeIfPresent(servers, forKey: .servers)
try container.encodeIfPresent(security, forKey: .security)
try extensionsContainer.encode(to: encoder)
}
}
|
/// The ComonadStore type class represents those Comonads that support local position information.
public protocol ComonadStore: Comonad {
/// Type of the position within the ComonadStore
associatedtype S
/// Obtains the current position of the store.
/// - Parameter wa: Value from which the store is retrieved.
/// - Returns: Current position.
static func position<A>(_ wa: Kind<Self, A>) -> S
/// Obtains the value stored in the provided position.
///
/// - Parameters:
/// - wa: Store.
/// - s: Position within the Store.
/// - Returns: Value stored in the provided position.
static func peek<A>(_ wa: Kind<Self, A>, _ s: S) -> A
}
public extension ComonadStore {
/// Obtains a value in a position relative to the current position.
///
/// - Parameters:
/// - wa: Store.
/// - f: Function to compute the relative position.
/// - Returns: Value located in a relative position to the current one.
static func peeks<A>(_ wa: Kind<Self, A>, _ f: @escaping (S) -> S) -> A {
peek(wa, f(position(wa)))
}
/// Moves to a new position.
///
/// - Parameters:
/// - wa: Store.
/// - s: New position.
/// - Returns: Store focused into the new position.
static func seek<A>(_ wa: Kind<Self, A>, _ s: S) -> Kind<Self, A> {
wa.coflatMap { fa in peek(fa, s) }
}
/// Moves to a new position relative to the current one.
///
/// - Parameters:
/// - wa: Store.
/// - f: Function to compute the new position, relative to the current one.
/// - Returns: Store focused into the new position.
static func seeks<A>(_ wa: Kind<Self, A>, _ f: @escaping (S) -> S) -> Kind<Self, A> {
wa.coflatMap { fa in peeks(fa, f) }
}
/// Extracts a collection of values from positions that depend on the current one.
///
/// - Parameters:
/// - wa: Store.
/// - f: Effectful function computing new positions based on the current one.
/// - Returns: A collection of values located a the specified positions.
static func experiment<F: Functor, A>(_ wa: Kind<Self, A>, _ f: @escaping (S) -> Kind<F, S>) -> Kind<F, A> {
F.map(f(position(wa))) { s in peek(wa, s) }
}
}
// MARK: Syntax for ComonadStore
public extension Kind where F: ComonadStore {
/// Obtains the current position of the store.
var position: F.S {
F.position(self)
}
/// Obtains the value stored in the provided position.
///
/// - Parameters:
/// - s: Position within the Store.
/// - Returns: Value stored in the provided position.
func peek(_ s: F.S) -> A {
F.peek(self, s)
}
/// Obtains a value in a position relative to the current position.
///
/// - Parameters:
/// - f: Function to compute the relative position.
/// - Returns: Value located in a relative position to the current one.
func peeks(_ f: @escaping (F.S) -> F.S) -> A {
F.peeks(self, f)
}
/// Moves to a new position.
///
/// - Parameters:
/// - s: New position.
/// - Returns: Store focused into the new position.
func seek(_ s: F.S) -> Kind<F, A> {
F.seek(self, s)
}
/// Moves to a new position relative to the current one.
///
/// - Parameters:
/// - f: Function to compute the new position, relative to the current one.
/// - Returns: Store focused into the new position.
func seeks(_ f: @escaping (F.S) -> F.S) -> Kind<F, A> {
F.seeks(self, f)
}
/// Extracts a collection of values from positions that depend on the current one.
///
/// - Parameters:
/// - f: Effectful function computing new positions based on the current one.
/// - Returns: A collection of values located a the specified positions.
func experiment<G: Functor>(_ f: @escaping (F.S) -> Kind<G, F.S>) -> Kind<G, A> {
F.experiment(self, f)
}
}
|
//
// ErrorViewController.swift
// RPGMill
//
// Created by William Young on 1/20/19.
// Copyright © 2019 William Young. All rights reserved.
//
import Cocoa
class ErrorViewController: NSViewController {
@IBOutlet weak var errorLabel: NSTextField!
var error: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
if let error = error {
errorLabel.stringValue = error
}
}
}
|
//
// NetworkManager.swift
// QuestionExample
//
// Created by Raidu on 7/22/20.
// Copyright © 2020 Raidu. All rights reserved.
//
import Foundation
import UIKit
enum Errors: Error {
case invalidURL
case invalidResponse(error:String)
case invalidData
}
// A global container for URL
struct URLConstants {
static let questionsURL = "https://opentdb.com/api.php?amount=10&category=9&difficulty=easy&type=multiple"
}
class Network {
static func getApiCallWithRequestURLString(requestString:String,completionBlock:@escaping((_ response:Data) -> Void), failureBlock:@escaping((_ error: Errors)->Void)) {
guard let url = URL(string: requestString) else {
failureBlock(.invalidURL)
return;
}
let dataTask = URLSession.shared.dataTask(with: url) { (responseData, httpResponse, error) in
if ( error == nil ) {
if ( responseData == nil || responseData?.count == 0 ) {
failureBlock(.invalidData)
}else {
completionBlock(responseData!)
}
}else {
failureBlock(.invalidResponse(error: error?.localizedDescription ?? ""))
}
}
dataTask.resume();
}
}
struct ShowAlert {
static func showAlert(_ title : String ,_ message : String) {
DispatchQueue.main.async {
guard let vc = UIApplication.shared.keyWindow?.rootViewController else {
return
}
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default)
alert.addAction(ok)
vc.present(alert, animated: true, completion: nil)
}
}
}
|
//
// ArticleCell.swift
// UpTech
//
// Created by A.Zinkov on 7/13/19.
// Copyright © 2019 ArtemZinkov. All rights reserved.
//
import RxSwift
import RxCocoa
class ArticleCell: UITableViewCell {
static let reuseIdentifier = "ArticleCell"
static let cellHeight: CGFloat = 120
static let formatter = DateFormatter()
@IBOutlet weak var articleImageView: UIImageView!
@IBOutlet weak var articleTitleLabel: UILabel!
@IBOutlet weak var articleDescriptionTextView: UITextView!
@IBOutlet weak var articleDateLabel: UILabel!
private(set) var disposeBag = DisposeBag()
private var viewModel: ArticleViewModelProtocol!
override func prepareForReuse() {
super.prepareForReuse()
articleImageView.image = nil
articleTitleLabel.text = nil
articleDescriptionTextView.text = nil
articleDateLabel.text = nil
disposeBag = DisposeBag()
}
func setup(with viewModel: ArticleViewModelProtocol) {
self.viewModel = viewModel
articleTitleLabel.text = viewModel.articleTitle
articleDescriptionTextView.text = viewModel.articleDescription
if let articleDate = viewModel.articleDate {
ArticleCell.formatter.dateFormat = "dd MMMM yyyy"
articleDateLabel.text = "Date: \(ArticleCell.formatter.string(from: articleDate))"
}
viewModel.articleImage.asObservable().subscribe(onNext: { [weak self] image in
guard let wself = self else { return }
wself.articleImageView.image = image?.resizeImage(targetSize: wself.articleImageView.bounds.size)
}, onError: { [weak self] error in
self?.articleImageView.image = nil
}).disposed(by: disposeBag)
}
}
|
//: [Previous](@previous)
import Foundation
protocol Named{
func fly()
}
class Coffee{
var name:String = ""
}
class Americano:Coffee{
var iced:Bool = false
}
var coffee = Coffee()
coffee = Americano()
var americano = Americano()
// americano = Coffee()
class Latte:Named{
var milk:Bool = false
func fly(){
print("fly")
}
}
var latte:Named = Latte()
latte.fly()
//: [Next](@next)
|
//
// MineInfoFilesOwner.swift
// SpecialTraining
//
// Created by 尹涛 on 2018/11/19.
// Copyright © 2018 youpeixun. All rights reserved.
//
import Foundation
class MineInfoFooterFilesowner: BaseFilesOwner {
override init() {
super.init()
}
}
|
//
// WhatsNewKit.swift
// weatherOrNot
//
// Created by John Gibson on 25/1/19.
// Copyright © 2019 John Gibson. All rights reserved.
//
import Foundation
import WhatsNewKit
//func whatsNewIfNeeded() {
// let items = [
// WhatsNew.Item(title: "Welcome", subtitle: "Nulla facilisi. Curabitur finibus eu nisl ut eleifend.", image: UIImage(named: "WhatsNew-Launch")),
// WhatsNew.Item(title: "Powered by Dark Sky", subtitle: "Fusce eget hendrerit nibh. Ut sodales aliquet auctor. Suspendisse vitae gravida nunc.", image: UIImage(named: "WhatsNew-DarkSky")),
// WhatsNew.Item(title: "Bug Fixes", subtitle: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed fermentum fermentum lectus, eu sagittis orci dictum eget.", image: UIImage(named: "WhatsNew-Dev")),
// WhatsNew.Item(title: "Themes", subtitle: "Mauris suscipit ipsum ex, id fermentum risus bibendum ac. Fusce viverra, sem nec dignissim elementum, massa lectus iaculis nisi, eu consectetur dui sapien aliquam nisi.", image: UIImage(named: "WhatsNew-Theme")),
// ]
//
// let myTheme = WhatsNewViewController.Theme { configuration in
// configuration.apply(animation: .fade)
// configuration.itemsView.imageSize = .fixed(height: 30)
//
// configuration.titleView.titleFont = .systemFont(ofSize: 42, weight: .heavy)
// configuration.titleView.secondaryColor = .init(
// startIndex: 11,
// length: 13,
// color: UIColor.whatsNewKitBlue
// )
//
// configuration.detailButton?.title = "Test"
// configuration.detailButton?.titleColor = Theme.current.textColour
// configuration.detailButton?.action = .website(url: "https://www.google.com")
//
// configuration.completionButton.title = "Ok, got it!"
// configuration.completionButton.action = .dismiss
//
// configuration.backgroundColor = Theme.current.backgroundColour
// configuration.titleView.titleColor = Theme.current.textColour
// configuration.itemsView.titleColor = Theme.current.textColour
// configuration.itemsView.subtitleColor = Theme.current.textColour
// }
//
// let myConfig = WhatsNewViewController.Configuration(theme: myTheme)
//
// let whatsNew = WhatsNew(title: "Welcome to \nweatherOrNot", items: items)
//
// let keyValueVersionStore = KeyValueWhatsNewVersionStore(keyValueable: UserDefaults.standard)
//
// let whatsNewVC = WhatsNewViewController(whatsNew: whatsNew, configuration: myConfig, versionStore: keyValueVersionStore)
//
// if let vc = whatsNewVC {
// self.present(vc, animated: true)
// }
//
// self.present(whatsNewVC, animated: true)
//}
|
import Foundation
struct Constants {
struct Storyboard {
static let homeViewController = "HomeVC"
static let signuploginview = "SignUpLogin"
static let alarm1View = "alarm1"
}
}
|
//
// User.swift
// twitter
//
// Created by Evelio Tarazona on 10/30/16.
// Copyright © 2016 Evelio Tarazona. All rights reserved.
//
import Foundation
public struct User: Persistable {
public typealias Source = NSDictionary
let sourceValue: NSDictionary
let id: String
let username: String
let name: String
let bio: String
let profileImage: URL?
let profileBackgroundImage: URL?
let website: URL?
let location: String
let protected: Bool
let verified: Bool
let following: Bool
let counts: UserCounts
public init(_ map: Source) {
sourceValue = map
id = map["id_str"] as? String ?? ""
username = map["screen_name"] as? String ?? ""
name = map["name"] as? String ?? ""
bio = map["description"] as? String ?? ""
profileImage = URL.from(map["profile_image_url_https"])
profileBackgroundImage = URL.from(map["profile_background_image_url_https"])
website = URL.from(map["url"])
location = map["location"] as? String ?? ""
protected = map["protected"] as? Bool ?? false
verified = map["verified"] as? Bool ?? false
following = map["following"] as? Bool ?? false
counts = UserCounts(map)
}
public func source() -> NSDictionary {
return sourceValue
}
}
extension URL {
static func from(_ value: Any?) -> URL? {
if let string = value as? String {
return URL(string: string)
}
return nil
}
}
struct UserCounts {
let tweets: UInt
let followers: UInt
let following: UInt
let favourites: UInt
init(_ map: NSDictionary) {
tweets = map["statuses_count"] as? UInt ?? 0
followers = map["followers_count"] as? UInt ?? 0
following = map["friends_count"] as? UInt ?? 0
favourites = map["favourites_count"] as? UInt ?? 0
}
}
|
//
// WordCount.swift
// WordCount
//
// Created by Sang Chul Lee on 2017. 3. 27..
// Copyright © 2017년 CodersHigh. All rights reserved.
//
import Foundation
class WordCount {
let words: String
init(words: String) {
self.words = words
}
func count() -> [String: Int] {
var result: [String: Int] = [:]
let wordArray = words.components(separatedBy: " ")
for word in wordArray {
var lowercasedWord = word.lowercased()
let puctuations = Array("~!@#$%^&*()_+|?/\\><,.;:\'\"[]{}`".characters)
/* remove puctuations in word */
for puctuation in puctuations {
for _ in 0..<lowercasedWord.characters.count {
if let idx = lowercasedWord.characters.index(of: puctuation) {
lowercasedWord.remove(at: idx)
} else {
break
}
}
}
/* add to the result dic */
if lowercasedWord != "" {
if result[lowercasedWord] == nil {
result[lowercasedWord] = 1
} else {
result[lowercasedWord] = result[lowercasedWord]! + 1
}
}
}
return result
}
}
|
//
// ThumbnailCollectionViewCell.swift
// HWS_100DoS_Project1a
//
// Created by Jeremy Fleshman on 8/8/20.
// Copyright © 2020 Jeremy Fleshman. All rights reserved.
//
// https://medium.com/@max.codes/programmatic-custom-collectionview-cell-subclass-in-swift-5-xcode-10-291f8d41fdb1
import UIKit
class ThumbnailCollectionViewCell: UICollectionViewCell {
static var identifier = "ThumbnailCollectionViewCell"
var picture: StormPicture? {
didSet {
guard let picture = picture else { return }
backgroundImage.image = picture.image
}
}
fileprivate let backgroundImage: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.layer.cornerRadius = 12
return imageView
}()
override init(frame: CGRect) {
super.init(frame: .zero)
self.contentView.addSubview(backgroundImage)
NSLayoutConstraint.activate([
backgroundImage.topAnchor.constraint(
equalTo: contentView.topAnchor
),
backgroundImage.bottomAnchor.constraint(
equalTo: contentView.bottomAnchor
),
backgroundImage.leadingAnchor.constraint(
equalTo: contentView.leadingAnchor
),
backgroundImage.trailingAnchor.constraint(
equalTo: contentView.trailingAnchor
),
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) not implemented")
}
}
|
//
// Circle Blvd.swift
// Circle Blvd
//
// Created by Phil Manijak on 4/3/15.
// Copyright (c) 2015 Secret Project LLC. All rights reserved.
//
import Foundation
import CoreData
class Circle: NSManagedObject {
@NSManaged var id: String
@NSManaged var name: String
}
|
//
// Static.swift
// skatecreteordieUITests
//
// Created by JAMES K ARASIM on 11/9/19.
// Copyright © 2019 JAMES K ARASIM. All rights reserved.
//
import Foundation
import XCTest
//use enum to store page objects
enum SkatecreteordieStaticMenu: String {
case mapButton = "map"
case detailsButton = "details"
var element: XCUIElement {
switch self {
case .mapButton, .detailsButton:
return XCUIApplication().tabBars.buttons[self.rawValue]
}
}
}
|
//
// SceneLoadable.swift
// list_up
//
// Created by eyexpo on 2017-07-06.
// Copyright © 2017 eyexpo. All rights reserved.
//
import SceneKit
public protocol SceneLoadable: class {
var scene: SCNScene? { get set }
}
|
/*
Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring (e.g.,"waterbottle"is a rotation of"erbottlewat").
*/
func isRotation(_ s1: String, _ s2: String) -> Bool {
func isSubstring(_ s1: String, _ s2: String) -> Bool{
for character in s2{
if s1.contains(character) == false{
return false
}
}
return true
}
if isSubstring(s1,s2) == true{
if s1.count != s2.count{
return false
}
//may be substring but may not be a rotation
var string1 = s1
var temp = ""
for i in 1..<s1.count{
let index = string1.index(string1.startIndex, offsetBy: i-1)
temp = String(string1.dropFirst(i)+string1[...index])
//print(temp)
if temp == s2{
return true
}
}
return false
}else{
//s2 can't be a rotation if not a substring of s1
return false
}
}
print(isRotation("waterbottle","cds")) //false
print(isRotation("waterbottle","water")) // false
print(isRotation("waterbottle","terbolttewa")) //false
print(isRotation("waterbottle","terbottlewa")) // true
|
//
// AppDelegate + UmengShare.swift
// niinfor
//
// Created by 王孝飞 on 2017/10/9.
// Copyright © 2017年 孝飞. All rights reserved.
//
import UIKit
extension AppDelegate{
}
extension AppDelegate{
func setUmengShare(_ appKey : String) {
///友盟统计
setAnalizy()
//打开友盟日志
//UMSocialManager.default().openLog(true)
UMSocialManager.default().umSocialAppkey = "5a961a7ba40fa3430d00001c"//"56a7807be0f55a7a19000cda"
UMSocialManager.default().umSocialAppSecret = ""
UMConfigure.setLogEnabled(true)
configUSharePlatforms()
}
private func setAnalizy() {
// UMAnalyticsConfig.sharedInstance().appKey = "5a961a7ba40fa3430d00001c"
//UMAnalyticsConfig.sharedInstance().channelId = "App Store"
// MobClick.start(withConfigure: UMAnalyticsConfig.sharedInstance())
// let dict = Bundle.main.infoDictionary
//
// let currentVersion = dict?["CFBundleShortVersionString"] as? String
//
// MobClick.setAppVersion(currentVersion)
///新版Version 5a961a7ba40fa3430d00001c
UMConfigure.initWithAppkey("5a961a7ba40fa3430d00001c", channel: "App Store")
// UMConfigure.sets
}
///设置分享平台
private func configUSharePlatforms() {
//
UMSocialManager.default().setPlaform(.wechatSession, appKey: "wxb9379cacd09b3e99", appSecret: "63b4ff9d26607c73556b0033379f2067", redirectURL: "http://mobile.umeng.com/social")
UMSocialManager.default().setPlaform(.QQ, appKey: "1104796793", appSecret: nil, redirectURL: nil)
//UMSocialManager.default().setPlaform(.sina, appKey: "", appSecret: "", redirectURL: "")//1106493842
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
let result = UMSocialManager.default().handleOpen(url, sourceApplication: sourceApplication, annotation: annotation)
if result == false {
}
return result
}
// func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject])
// -> Bool {
//
//
// return result
// }
// - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
let result = UMSocialManager.default().handleOpen(url)
if result == false {
}
return result
}
///分享按钮
class func shareUrl(_ url : String , imageString : String , title : String , descriptionString : String, viewController : BaseViewController ,_ type : UMSocialPlatformType) {
UMSocialUIManager.showShareMenuViewInWindow { (plateform, userInfo) in
let messageObject = UMSocialMessageObject()
//使用的图像
let thumnail = UIImage(named: imageString)
if thumnail == nil {
let imageView = UIImageView()
if let urls = URL(string: imageString) {
imageView.sd_setImage(with:urls)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
umnegShare(thumnail: imageView.image ?? #imageLiteral(resourceName: "24321528943095_.pic"), url: url, title: title, descriptionString: descriptionString, messageObject: messageObject, plateform: plateform, viewController: viewController)
})
}else {
umnegShare(thumnail: #imageLiteral(resourceName: "24321528943095_.pic"), url: url, title: title, descriptionString: descriptionString, messageObject: messageObject, plateform: plateform, viewController: viewController)
}
}else{
umnegShare(thumnail: thumnail!, url: url, title: title, descriptionString: descriptionString, messageObject: messageObject, plateform: plateform, viewController: viewController)
}
}
}
private class func umnegShare(thumnail : UIImage , url : String, title : String , descriptionString : String, messageObject : UMSocialMessageObject ,plateform : UMSocialPlatformType ,viewController : BaseViewController ) {
let shareObject = UMShareWebpageObject.shareObject(withTitle: title, descr: descriptionString, thumImage: thumnail)
shareObject?.webpageUrl = url
messageObject.shareObject = shareObject
UMSocialManager.default().share(to: plateform , messageObject: messageObject, currentViewController: viewController) { (data , error ) in
if error != nil {
print(error ?? "" )
}else{
if let data = data as? UMSocialShareResponse {
print(data.message)
//第三方原始返回的数据
print(data.originalResponse)
}
}
}
}
// ///分享按钮
// class func shareUrl(_ url : String , imageString : String , title : String , descriptionString : String, viewController : BaseViewController ,_ type : UMSocialPlatformType) {
//
// UMSocialUIManager.showShareMenuViewInWindow { (plateform, userInfo) in
//
//
// let messageObject = UMSocialMessageObject()
//
// //使用的图像
// let thumnail = UIImage(named: imageString)
//
// let shareObject = UMShareWebpageObject.shareObject(withTitle: title, descr: descriptionString, thumImage: thumnail)
//
// shareObject?.webpageUrl = url
//
// messageObject.shareObject = shareObject
//
// UMSocialManager.default().share(to: plateform , messageObject: messageObject, currentViewController: viewController) { (data , error ) in
//
// if error != nil {
// print(error ?? "" )
// }else{
//
// if let data = data as? UMSocialShareResponse {
//
// print(data.message)
// //第三方原始返回的数据
// print(data.originalResponse)
// }
// }
// }
// }
// }
// func open(_ url: URL, options: [String : Any] = [:], completionHandler completion: ((Bool) -> Void)? = nil){
//
// let result = UMSocialManager.default().handleOpen(url, sourceApplication: options, annotation: nil)
//
//
// }
// func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
//
// let result = UMSocialManager.default().handleOpen(url, sourceApplication: sourceApplication, annotation: annotation)
//
// if result == false {
//
// }
//
// return result
// }
// 支持所有iOS系统
// application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
// {
// BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
// if (!result) {
// // 其他如支付等SDK的回调
// }
// return result;
// }
}
|
//
// ImageDownloadManager.swift
// PhonePe
//
// Created by Sudhanshu Singh on 15/02/20.
// Copyright © 2020 self. All rights reserved.
//
import UIKit
class LogoImageDownloadManager {
private init() {
}
class func fetchLogoImageData(fromUrl url: URL, completionHandler: @escaping (_ image: UIImage?) -> Void) {
let dataTask = URLSession.shared.dataTask(with: url) { (data, resposne, error) in
if let downloadData = data, let image = UIImage(data: downloadData) {
completionHandler(image)
return
}
completionHandler(nil)
}
dataTask.resume()
}
}
|
//
// TravelDB+CoreDataProperties.swift
// TravelApp
//
// Created by User on 8/9/21.
//
//
import Foundation
import CoreData
public class TravelDB: NSManagedObject {
}
extension TravelDB {
@nonobjc public class func fetchRequest() -> NSFetchRequest<TravelDB> {
return NSFetchRequest<TravelDB>(entityName: "TravelDB")
}
@NSManaged public var date: String?
@NSManaged public var descr: String?
@NSManaged public var id: String?
@NSManaged public var name: String?
@NSManaged public var imagesData: Data?
@NSManaged public var user: UserDB?
}
|
//
// FMDBManager.swift
// Langu.ag
//
// Created by Huijing on 14/12/2016.
// Copyright © 2016 Huijing. All rights reserved.
//
import Foundation
import FMDB
class FMDBManager{
var fileURL: URL!
var database : FMDatabase!
init(){
let fileURL = try! FileManager.default
.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent(Constants.DB_NAME)
database = FMDatabase(path: fileURL.path)
if(database == nil)
{
return
}
database.open()
createTables()
database.close()
}
func createTables()
{
do {
//create categories table
try database.executeUpdate(createTableString(tableName:EventModel.localTableName, tableObject: EventModel.localTableObject, primaryKey: EventModel.localTablePrimaryKey), values: nil)
} catch {
print("failed: \(error.localizedDescription)")
}
}
func emptyTables()
{
do{
database.open()
try database.executeUpdate("DELETE FROM " + EventModel.localTableName, values: nil)
database.close()
}
catch{
print("failed: \(error.localizedDescription)")
}
}
func executeQuery(_ query : String) {
do{
database.open()
try database.executeUpdate(query, values: nil)
database.close()
}
catch{
print("failed: \(error.localizedDescription)")
}
}
func createTableString(tableName: String, tableObject: [String: String], primaryKey: String) -> String{
//let tableDict = tableObject as! NSDictionary
//let keys = tableDict.allKeys
var resultString = "CREATE TABLE IF NOT EXISTS " + tableName + "("
for (key, value) in tableObject{
if(key != primaryKey){
resultString = resultString + key + " " + value + " ,"
}
else{
resultString = resultString + key + " " + value + " PRIMARY KEY ,"
}
}
resultString.remove(at: resultString.index(before: resultString.endIndex))
resultString.append(")")
return resultString
}
func insertOrUpdateRecordQuery(tableObject: [String: String], tableName: String, tableData: [String: AnyObject], primaryKey: String) -> String{
var insertString = "INSERT OR REPLACE INTO \(tableName) "
var keysString = "("
var valuesString = "("
for (key,_) in tableObject{
keysString.append("\(key),")
valuesString += " '"
if(key == primaryKey){
let valueString1 = "\(tableData[key] as AnyObject)".replacingOccurrences(of: "'", with: "''")
valuesString += ("(SELECT \(key) FROM \(tableName) where \(key)= \(valueString1))")
}
else{
valuesString += ("\(tableData[key] as AnyObject)").replacingOccurrences(of: "'", with: "''")
}
valuesString += "' ,"
}
keysString.remove(at: keysString.index(before: keysString.endIndex))
keysString.append(") values ")
valuesString.remove(at: valuesString.index(before: valuesString.endIndex))
valuesString.append(")")
insertString.append(keysString)
insertString.append(valuesString.replacingOccurrences(of: "Optional(", with: "").replacingOccurrences(of: ")',", with: "',"))
return insertString
}
func getDataFromFMDB(with query: String, tableObject: [String: String]) -> [AnyObject]{
var result : [AnyObject] = []
database.open()
do{
let rs = try database.executeQuery(query, values: nil)
while rs.next(){
var resultItem : [String: AnyObject] = [:]
for item in tableObject{
resultItem[item.key] = getObjectFromKey(value: rs, type: item.value, key: item.key)
}
result.append(resultItem as AnyObject)
}
}catch {
print("failed: \(error.localizedDescription)")
}
database.close()
return result
}
func getObjectFromKey(value: FMResultSet, type: String, key: String) -> AnyObject{
if (type.hasPrefix("VARCHAR")){
return value.string(forColumn: key) as AnyObject
}
else if (type.hasPrefix("TEXT")){
return value.string(forColumn: key) as AnyObject
}
else if(type.hasPrefix("TINYINT")){
return value.bool(forColumn: key) as AnyObject
}
else if(type.hasPrefix("BIGINT")){
return value.longLongInt(forColumn: key) as AnyObject
}
else if(type.hasPrefix("INT"))
{
return Int(value.string(forColumn: key)) as AnyObject
}
else if(type.hasPrefix("DOUBLE"))
{
return Double(value.string(forColumn: key)) as AnyObject
}
return "" as AnyObject
}
}
var fmdbManager = FMDBManager()
|
//
// IceCandidatePair.swift
// Callstats
//
// Created by Amornchai Kanokpullwad on 10/3/18.
// Copyright © 2018 callstats. All rights reserved.
//
import Foundation
import WebRTC
/**
ICE candidate pair info for some event
*/
struct IceCandidatePair: Encodable {
let id: String
let localCandidateId: String
let remoteCandidateId: String
let state: String
let priority: Int
let nominated: Bool
init(stats: WebRTCStats) {
// Please note that this stats is not updated yet and might not be able to send correct value
self.id = stats.id
self.localCandidateId = stats.values["localCandidateId"] ?? ""
self.remoteCandidateId = stats.values["remoteCandidateId"] ?? ""
// `succeeded` will be sent if connection is active, `waiting` otherwise
let isActive = stats.values["googActiveConnection"] == "true"
let state = isActive ? "succeeded" : "waiting"
self.state = state
self.nominated = isActive
// no priority available
self.priority = 0
}
}
|
//
// Punch.swift
// Contech
//
// Created by Lauren Shultz on 7/6/18.
// Copyright © 2018 Lauren Shultz. All rights reserved.
//
import Foundation
import UIKit
struct Punch {
var point: Point?
var title: String
var sub: String
var trade: Trade
var project: String
var author: String
var note: String
var id: String
var image: UIImage
// init (id: String, title: String, trade: Trade, project: Project, author: User) {
// self.title = title
// self.id = id
// self.trade = trade
// self.project = project
// self.author = author
// }
// func apply(point: Point?, sub: Sub?, note: String?, image: UIImage?) {
// if (point != nil) {
// self.point = point!
// }
// if (sub != nil) {
// self.sub = sub!
// }
// if (note != nil) {
// self.note = note!
// }
// if (image != nil) {
// self.image = image!
// }
// }
}
extension Punch {
enum SerializationError:Error {
case missing(String)
case invalid(String, Any)
}
init?(json: [String: Any]) throws {
print("structing")
guard let id = json["id"] as? Int,
let point = json["point"] as? String,
let title = json["title"] as? String,
let sub = json["sub"] as? String,
let project = json["project"] as? String,
let author = json["author"] as? String,
let note = json["note"] as? String,
let image = json["image"] as? String,
let trade = json["trade"] as? String
else {
print("error")
throw SerializationError.missing("Value id missing for x")
}
self.id = String(id)
var point_vectors = point.split(separator: ",").map(String.init)
self.point = Point(x: Float(point_vectors[0])!, y: Float(point_vectors[1])!, z: Float(point_vectors[2]))
self.title = title
self.project = project
self.sub = sub
self.author = author
self.note = note
self.image = #imageLiteral(resourceName: "ContechLogo")//UIImage(data: Data(base64Encoded: image)!)!
self.trade = Trade(title: trade)
}
static func getAccountInfo (withId id:String, completion: @escaping (Punch?) -> ()) {
let request = APIDelegate.requestBuilder(withPath: APIDelegate.punchesPath, withId: id, methodType: "GET", postContent: nil)
if(request == nil) {
completion(nil)
}
let task = URLSession.shared.dataTask(with: request!, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in
var targetPunch: Punch? = nil
if let data = data {
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
if let punchObject = try? Punch(json: json) {
targetPunch = punchObject!
}
}
} catch {
print("error")
print(error)
}
DispatchQueue.main.async {
completion(targetPunch)
}
}
})
task.resume()
}
static func patch(id: String, body: [String], completion: @escaping (Punch?) -> ()) {
let request = APIDelegate.requestBuilder(withPath: APIDelegate.punchesPath, withId: id, methodType: "PATCH", postContent: APIDelegate.buildPostString(body: body))
if(request == nil) {
completion(nil)
}
let task = URLSession.shared.dataTask(with: request!, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in
var targetPunch:Punch? = nil
print("In Task.")
if let data = data {
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
print("JSON: ", json)
if let punchObject = try? Punch(json: json) {
targetPunch = punchObject!
}
}
} catch {
print("error in creation")
print(error)
}
DispatchQueue.main.async {
completion(targetPunch)
}
}
})
task.resume()
}
static func createNew(body: [String], completion: @escaping (Punch?) -> ()) {
let request = APIDelegate.requestBuilder(withPath: APIDelegate.punchesPath, withId: "1", methodType: "POST", postContent: APIDelegate.buildPostString(body: body))
if(request == nil) {
completion(nil)
}
let task = URLSession.shared.dataTask(with: request!, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in
var targetPunch:Punch? = nil
print("In Task.")
if let data = data {
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
print("JSON: ", json)
if let punchObject = try? Punch(json: json) {
targetPunch = punchObject!
}
}
} catch {
print("error in creation")
print(error)
}
DispatchQueue.main.async {
completion(targetPunch)
}
}
})
task.resume()
}
static func all (withId id:String, completion: @escaping ([Punch]) -> ()) {
let request = APIDelegate.requestBuilder(withPath: APIDelegate.punchesPath, withId: "1", methodType: "GET", postContent: nil)
let task = URLSession.shared.dataTask(with: request!, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in
var targetPunches:[Punch] = []
if let data = data {
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String:Any]] {
for punch in json {
if let punchObject = try? Punch(json: punch) {
targetPunches.append(punchObject!)
}
}
}
} catch {
print("error")
print(error)
}
completion(targetPunches)
}
})
task.resume()
}
// static func apply(point: Point?, sub: Sub?, note: String?, image: UIImage?) {
// if (point != nil) {
// self.point = point!
// }
// if (sub != nil) {
// self.sub = sub!
// }
// if (note != nil) {
// self.note = note!
// }
// if (image != nil) {
// self.image = image!
// }
// }
}
|
//
// main.swift
// FactoryGenerator
//
// Created by Ihara Takeshi on 2018/06/06.
// Copyright © 2018 Nonchalant. All rights reserved.
//
import Commander
import Core
import Generator
import Parser
let main = command(
VariadicOption<String>("exclude", description: "The path of excluded *.swift"),
VariadicOption<String>("testable", description: "The name of testable target"),
Option("output", default: "./Factories.generated.swift", description: "The generated path of output"),
VariadicArgument<String>("The path of input *.swift")
) { excludes, testables, output, includes in
let options = Options(includes: includes, excludes: excludes, testables: testables, output: output)
do {
let types = try Parser(paths: options.inputs).run()
try Generator(types: types).run(with: options)
} catch let error {
switch error {
case _ as ParseError:
print("Parse Error is occured 😱")
case _ as GenerateError:
print("Generate Error is occured 😱")
default:
print("Unknown Error is occured 😱")
}
return
}
print("\(options.output) is generated 🎉")
}
main.run(Version.current)
|
//
// Created by Naoyuki Seido on 2017/03/12.
// Copyright (c) 2017 Naoyuki Seido. All rights reserved.
//
import AppKit
class MyScrollView : NSScrollView {
override class func contentSize(forFrameSize fSize: NSSize, horizontalScrollerClass: AnyClass?, verticalScrollerClass: AnyClass?, borderType type: NSBorderType, controlSize: NSControlSize, scrollerStyle: NSScrollerStyle) -> NSSize {
return super.contentSize(forFrameSize: fSize, horizontalScrollerClass: horizontalScrollerClass, verticalScrollerClass: verticalScrollerClass, borderType: type, controlSize: controlSize, scrollerStyle: scrollerStyle)
}
var ignoreScroll : Bool = false
override func reflectScrolledClipView(_ cView: NSClipView) {
if !ignoreScroll {
super.reflectScrolledClipView(cView)
}
}
}
|
//
// MapMeetingViewController.swift
// TopSpin
//
// Created by Andrey Artemenko on 23/08/2017.
//
import UIKit
import MapKit
class MapMeetingViewController: BaseViewController {
fileprivate var frc: NSFetchedResultsController<NSFetchRequestResult>?
fileprivate let mapView = TSMapView()
fileprivate let initialLocation = CLLocation(latitude: 55.752017, longitude: 37.617270)
fileprivate var regionRadius: CLLocationDistance = 20_000
fileprivate var usualRadius: CLLocationDistance = 2000
fileprivate let cellHeight: CGFloat = 168
fileprivate var meetings = [Meeting]()
fileprivate var isLoading = false
fileprivate var isNeedUpdate = false
fileprivate var meeting: Meeting?
lazy var collectionView: MapCollectionView = {
[unowned self] in
let flow = UICollectionViewFlowLayout()
flow.minimumLineSpacing = 8
let collectionView = MapCollectionView(frame: self.view.bounds, collectionViewLayout: flow)
collectionView.backgroundColor = .clear
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.dataSource = self
collectionView.delegate = self
collectionView.alwaysBounceVertical = true
collectionView.contentInset.top = screenSize.height
collectionView.showsVerticalScrollIndicator = false
collectionView.register(MeetingFeedCollectionViewCell.self)
return collectionView
}()
class func create(with meeting: Meeting) -> MapMeetingViewController {
let vc = MapMeetingViewController()
vc.meeting = meeting
return vc
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
mapView.frame = view.bounds
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.delegate = self
mapView.showsUserLocation = true
mapView.showsCompass = true
view.addSubview(mapView)
initFRC()
configureAnnotations()
view.addSubview(collectionView)
centerMapOnLocation(initialLocation, radius: regionRadius)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
var radius = regionRadius
if meeting != nil {
radius = usualRadius
} else if let r = Session.shared.meetingFilter.radius?.doubleValue {
radius = r
}
centerMapOnLocation(meeting?.court?.location ?? LocationManager.shared.location ?? initialLocation, radius: radius)
}
func centerMapOnLocation(_ location: CLLocation, radius: CLLocationDistance) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, radius * 2.0, radius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
func loadMeetings(at location: CLLocationCoordinate2D, radius: Float) {
if isLoading {
API.shared.cancelRequest(.GET, path: MeetingPaths.mettings.rawValue)
}
isLoading = true
let filter = Meeting.Filter(location: location, radius: NSNumber(value: radius * 0.5), gender: Session.shared.meetingFilter.gender, minLevel: Session.shared.meetingFilter.minLevel, maxLevel: Session.shared.meetingFilter.maxLevel)
Meeting.getMeetings(with: .forgo, filter: filter, fromMap: true) { [weak self] (meetings, error) in
if let stronSelf = self {
stronSelf.isLoading = false
}
}
}
func initFRC() {
let predicate = NSPredicate(format: "%K.%K != %@ AND %K != nil", MeetingRelationships.owner.rawValue, UserAttributes.userId.rawValue, Session.shared.userId ?? 0, MeetingAttributes.meetingId.rawValue)
frc = Meeting.mr_fetchAllSorted(by: "court.courtId,timeStart", ascending: true, with: predicate, groupBy: "court.courtId", delegate: self)
do {
try frc?.performFetch()
} catch {
print("")
}
}
func configureAnnotations() {
mapView.removeAnnotations(mapView.annotations)
guard let count = frc?.sections?.count else {
return
}
for section in 0..<count {
let indexPath = IndexPath(item: 0, section: section)
if let annotation = frc?.object(at: indexPath) as? Meeting, let numberOfPoint = frc?.sections?[section].numberOfObjects {
annotation.annotationCount = numberOfPoint
annotation.section = section
mapView.addAnnotation(annotation)
}
}
}
func showMeetings(at section: Int) {
guard let numberOfObjects = frc?.sections?[section].numberOfObjects else {
return
}
for item in 0..<numberOfObjects {
if let meeting = frc?.object(at: IndexPath(item: item, section: section)) as? Meeting {
meetings.append(meeting)
}
}
collectionView.performBatchUpdates({
self.collectionView.reloadSections(IndexSet(integer: 0))
}) { (finish) in
if finish {
let y = self.meetings.count > 1 ? self.cellHeight + 68 : self.cellHeight + 48
self.collectionView.setContentOffset(CGPoint(x: 0, y: -(screenSize.height - y)), animated: true)
}
}
}
func hideMeetings() {
meetings.removeAll()
collectionView.reloadSections(IndexSet(integer: 0))
}
}
extension MapMeetingViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
loadMeetings(at: mapView.region.center, radius: Float(mapView.radius))
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation.isKind(of: MKUserLocation.self) {
var pin = mapView.dequeueReusableAnnotationView(withIdentifier: "myPinView")
if pin == nil {
pin = MKAnnotationView(annotation: annotation, reuseIdentifier: "myPinView")
}
pin?.image = UIImage(named: "ic_pin_my_cort")
return pin
}
var pin = mapView.dequeueReusableAnnotationView(withIdentifier: "pinView")
if pin == nil {
pin = MeetingAnnotationView(annotation: annotation, reuseIdentifier: "pinView")
}
pin?.image = (pin?.isSelected)! ? UIImage(named: "ic_pin_cort_active") : UIImage(named: "ic_pin_cort")
return pin
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if view.annotation?.isKind(of: MKUserLocation.self) == true {
return
}
view.image = UIImage(named: "ic_pin_cort_active")
UIView.animate(withDuration: 0.3) {
view.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
}
if let annotation = view.annotation as? Meeting, let section = annotation.section {
showMeetings(at: section)
}
}
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
if view.annotation?.isKind(of: MKUserLocation.self) == true {
return
}
view.image = UIImage(named: "ic_pin_cort")
UIView.animate(withDuration: 0.3) {
view.transform = CGAffineTransform.identity
}
hideMeetings()
}
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
guard let meeting = meeting else {
return
}
mapView.selectAnnotation(meeting, animated: true)
}
}
extension MapMeetingViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
isNeedUpdate = false
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
if type == .insert || type == .delete {
isNeedUpdate = true
}
if type == .update && meetings.count > 0 {
collectionView.reloadData()
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
if isNeedUpdate {
configureAnnotations()
}
}
}
extension MapMeetingViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width - 16, height: cellHeight)
}
}
extension MapMeetingViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return meetings.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return collectionView.dequeueReusableCell(MeetingFeedCollectionViewCell.self, forIndexPath: indexPath)
}
}
extension MapMeetingViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let cell = cell as? MeetingFeedCollectionViewCell, meetings.count > indexPath.item {
cell.meeting = meetings[indexPath.item]
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if meetings.count > indexPath.item {
let meeting = meetings[indexPath.item]
navigationController?.pushViewController(MeetingViewController.create(with: meeting), animated: true)
}
}
}
extension MapMeetingViewController: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y < -(screenSize.height - 60), let annotation = mapView.selectedAnnotations.first as? Meeting {
mapView.deselectAnnotation(annotation, animated: true)
}
}
}
class MeetingAnnotationView: MKAnnotationView {
let label = UILabel()
override var annotation: MKAnnotation? {
didSet {
if let an = annotation as? Meeting, let count = an.annotationCount {
label.text = count > 1 ? "\(count)" : ""
} else {
label.text = ""
}
}
}
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
label.frame = frame
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 20, weight: UIFontWeightMedium)
label.textAlignment = .center
addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var isSelected: Bool {
didSet {
if isSelected {
label.frame.origin.y -= 4
} else {
label.frame.origin.y = 0
}
}
}
}
class MapCollectionView: UICollectionView {
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let hitView = super.hitTest(point, with: event)
if point.y < 0 {
return nil
}
return hitView
}
}
|
import XCTest
import GameEngineTests
var tests = [XCTestCaseEntry]()
tests += GameEngineTests.allTests()
XCTMain(tests)
|
import Foundation
struct StoryBrain {
let stories = [
Story( //0
story: "Your car has blown a tire on a winding road in the middle of nowhere with no cell phone reception. You decide to hitchhike. A rusty pickup truck rumbles to a stop next to you. A man with a wide-brimmed hat and soulless eyes opens the passenger door for you and says: 'Need a ride, boy?'.",
firstOption: "I'll hop in. Thanks for the help!", pathFirstOption : 2,
secondOption: "Well, I don't have many options. Better ask him if he's a murderer.", pathSecondOption: 1
),
Story( //1
story: "He nods slowly, unphased by the question.",
firstOption: "At least he's honest. I'll climb in.", pathFirstOption: 2,
secondOption: "Wait, I know how to change a tire.", pathSecondOption: 3
),
Story( //2
story: "As you begin to drive, the stranger starts talking about his relationship with his mother. He gets angrier and angrier by the minute. He asks you to open the glove box. Inside you find a bloody knife, two severed fingers, and a cassette tape of Elton John. He reaches for the glove box.",
firstOption: "I love Elton John! Hand him the cassette tape.", pathFirstOption: 5,
secondOption: "It’s him or me. Take the knife and stab him.", pathSecondOption: 4
),
Story( //3
story: "What? Such a cop-out! Did you know accidental traffic accidents are the second leading cause of",
firstOption: "The", pathFirstOption: 0,
secondOption: "End", pathSecondOption: 0
),
Story( //4
story: "As you smash through the guardrail and careen towards the jagged rocks below you reflect on the dubious wisdom of stabbing someone while they are driving a car you are in.",
firstOption: "The", pathFirstOption: 0,
secondOption: "End", pathSecondOption: 0
),
Story( //5
story: "You bond with the murderer while crooning verses of 'Can you feel the love tonight'. He drops you off at the next town. Before you go he asks you if you know any good places to dump bodies. You reply: 'Try the pier.'",
firstOption: "The", pathFirstOption: 0,
secondOption: "End", pathSecondOption: 0
)
]
var path = 0
mutating func nextStory(_ userOption : String){
if userOption == stories[path].firstOption {
path = stories[path].pathFirstOption!
} else {
path = stories[path].pathSecondOption!
}
}
func getStory() -> String {
return stories[path].story
}
func getFirstOption() -> String? {
return stories[path].firstOption
}
func getSecindOption() -> String? {
return stories[path].secondOption
}
}
|
import UIKit
//Write a function that accepts a String as its only parameter,
//and returns true if the string has
//only unique letters, taking letter case into account.
func unique_letters(input:String) -> Bool {
let result = Set(input)
return result.count == input.count
}
unique_letters(input: "abc")
unique_letters(input: "abca")
|
// RUN: %target-swift-frontend -emit-sil %s | FileCheck %s
// Make sure that we are able to inline try-apply instructions.
@_transparent
public func foo() throws -> Int32 {
return 999
}
// CHECK-LABEL: _TF12throw_inline3foo
// CHECK: %0 = integer_literal $Builtin.Int32, 999
// CHECK: %1 = struct $Int32 (%0 : $Builtin.Int32)
// CHECK: return %1 : $Int32
func bar() throws -> Int32 {
return try foo()
}
|
//
// Playlist+Convinience.swift
// PlaylistCoreData
//
// Created by Jordan Lamb on 9/25/19.
// Copyright © 2019 Squanto Inc. All rights reserved.
//
import Foundation
import CoreData
extension Playlist {
convenience init(playlistName: String, songs:[Song] = [], moc: NSManagedObjectContext = CoreDataStack.context) {
self.init(context: moc)
self.playlistName = playlistName
}
}
|
//
// ResponseNotific.swift
// MockApp
//
// Created by Egor Gorskikh on 08.09.2021.
//
import Foundation
enum ResponseServer {
case succes
case error
}
|
//
// BaseDataContainViewController.swift
// J.Todo
//
// Created by JinYoung Lee on 2019/12/19.
// Copyright © 2019 JinYoung Lee. All rights reserved.
//
import Foundation
import UIKit
class BaseDataContainViewController: UIViewController {
internal var todoViewModel: TodoViewModel = ModelContainer.Instance.ViewModel
internal var initialize: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
setNavigationBar()
}
internal func setNavigationBar() {
navigationController?.navigationBar.tintColor = UIColor.white
}
}
|
import XCTest
import InfoCoreTests
var tests = [XCTestCaseEntry]()
tests += InfoCoreTests.allTests()
XCTMain(tests)
|
//
// Contacts.swift
// proj4
//
// Created by Joseph Ham on 4/5/21.
// Copyright © 2021 Sam Spohn. All rights reserved.
//
import SwiftUI
import MessageUI
import mailgun
import CoreData
/// Contacts View
struct ContactViewMain: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(fetchRequest: Contact_.allContactsFetchRequest()) var contactList: FetchedResults<Contact_>
@State private var text = ""
var body: some View {
NavigationView {
List{
Section(header: Text("Contacts")) {
ForEach(self.contactList) { con in
NavigationLink(destination: EditView(contact: con)) {
VStack(alignment: .leading) {
Text(con.email ?? "")
.font(.headline)
}
}
}
.onDelete { (indexSet) in // Delete gets triggered by swiping left on a row
// ❇️ Gets the BlogIdea instance out of the blogIdeas array
// ❇️ and deletes it using the @Environment's managedObjectContext
let toDelete = self.contactList[indexSet.first!]
self.managedObjectContext.delete(toDelete)
do {
try self.managedObjectContext.save()
} catch {
print(error)
}
}
}
.font(.headline)
}
.listStyle(GroupedListStyle())
.navigationBarTitle(Text("Contact List"))
.navigationBarItems(trailing: EditButton())
}
}
}
struct ContactViewMain_Previews: PreviewProvider {
static var previews: some View {
Group {
ContactViewMain()
}
}
}
|
//
// Server.swift
// Big Brain Team
//
// Created by Nick Oltyan on 10.10.2021.
//
import UIKit
class Server {
func fetchData(forRisk risk: PortfelRisk, andDiv div: PortfelDiversification, completion: @escaping ([String:Any]?, Error?) -> Void) {
let normalURL = URL(string: "httsp://bbt-vtb.herokuapp.com/")!
let riskURL = URL(string: "https://bbt-vtb.herokuapp.com/?case=risk")!
let divURL = URL(string: "https://bbt-vtb.herokuapp.com/?case=div")!
if risk == .risk {
let task = URLSession.shared.dataTask(with: riskURL) { (data, response, error) in
guard let data = data else { return }
do {
if let array = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any] {
completion(array, nil)
}
} catch {
print(error)
completion(nil, error)
}
}
task.resume()
}
else if div == .notDiversified {
let task = URLSession.shared.dataTask(with: divURL) { (data, response, error) in
guard let data = data else { return }
do {
if let array = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any] {
completion(array, nil)
}
} catch {
print(error)
completion(nil, error)
}
}
task.resume()
}
else {
let task = URLSession.shared.dataTask(with: normalURL) { (data, response, error) in
guard let data = data else { return }
do {
if let array = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any] {
completion(array, nil)
}
} catch {
print(error)
completion(nil, error)
}
}
task.resume()
}
}
}
|
//
// BannerView.swift
// Brunel
//
// Created by Aaron McTavish on 20/01/2016.
// Copyright © 2016 ustwo Fampany Ltd. All rights reserved.
//
import UIKit
final class BannerView: BaseStackView {
// MARK: - Properties
let banner = ClockBannerView()
// MARK: - Setup
override func setup() {
super.setup()
#if os(iOS)
backgroundColor = UIColor.white
#endif
stackView.distribution = .fill
stackView.spacing = 0.0
stackView.addArrangedSubview(banner)
}
override func setupConstraints() {
super.setupConstraints()
#if os(tvOS)
contentInsets = UIEdgeInsets(top: Constants.Layout.HalfMargin, left: 0.0, bottom: 0.0, right: 0.0)
#endif
}
}
final class ClockBannerView: BaseView {
// MARK: - Properties
let clock = ClockLabel()
// MARK: - Setup
override func setup() {
super.setup()
backgroundColor = Constants.Colors.BlueColor
clock.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .vertical)
clock.textAlignment = .center
clock.textColor = UIColor.white
addSubview(clock)
}
// MARK: - Layout
override func setupConstraints() {
super.setupConstraints()
// Turn off autoresizing mask
clock.translatesAutoresizingMaskIntoConstraints = false
// View Dictionary
let views = ["clock": clock]
let metrics = Constants.Layout.Metrics
// Vertical Constraints
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-HalfMargin-[clock]-HalfMargin-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
// Horizontal Constraints
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-HalfMargin-[clock]-HalfMargin-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
}
}
|
//
// String+Mapper.swift
//
import Foundation
extension String {
public func map<D: Decodable>(_ type: D.Type) -> D? {
let decoder = JSONDecoder()
guard let jsonData = data(using: .utf8), !jsonData.isEmpty else {
return nil
}
do {
return try decoder.decode(D.self, from: jsonData)
} catch {
return nil
}
}
var urlParameterEncoded: String {
let generalDelimitersToEncode = ":#[]@"
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)!
}
}
|
@testable import TMDb
import XCTest
final class SearchServiceTests: XCTestCase {
var service: SearchService!
var apiClient: MockAPIClient!
override func setUp() {
super.setUp()
apiClient = MockAPIClient()
service = SearchService(apiClient: apiClient)
}
override func tearDown() {
apiClient = nil
service = nil
super.tearDown()
}
func testSearchAllWithDefaultParametersReturnsMedia() async throws {
let query = String.randomString
let expectedResult = MediaPageableList.mock()
apiClient.result = .success(expectedResult)
let result = try await service.searchAll(query: query)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.multi(query: query).path)
}
func testSearchAllReturnsMedia() async throws {
let query = String.randomString
let expectedResult = MediaPageableList.mock()
apiClient.result = .success(expectedResult)
let result = try await service.searchAll(query: query, page: nil)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.multi(query: query).path)
}
func testSearchAllWithPageReturnsMedia() async throws {
let query = String.randomString
let expectedResult = MediaPageableList.mock()
let page = expectedResult.page
apiClient.result = .success(expectedResult)
let result = try await service.searchAll(query: query, page: page)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.multi(query: query, page: page).path)
}
func testSearchMoviesWithDefaultParametersReturnsMovies() async throws {
let query = String.randomString
let expectedResult = MoviePageableList.mock()
apiClient.result = .success(expectedResult)
let result = try await service.searchMovies(query: query)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.movies(query: query).path)
}
func testSearchMoviesReturnsMovies() async throws {
let query = String.randomString
let expectedResult = MoviePageableList.mock()
apiClient.result = .success(expectedResult)
let result = try await service.searchMovies(query: query, year: nil, page: nil)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.movies(query: query).path)
}
func testSearchMoviesWithYearReturnsMovies() async throws {
let query = String.randomString
let year = 2020
let expectedResult = MoviePageableList.mock()
apiClient.result = .success(expectedResult)
let result = try await service.searchMovies(query: query, year: year, page: nil)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.movies(query: query, year: year).path)
}
func testSearchMoviesWithPageReturnsMovies() async throws {
let query = String.randomString
let expectedResult = MoviePageableList.mock()
let page = expectedResult.page
apiClient.result = .success(expectedResult)
let result = try await service.searchMovies(query: query, year: nil, page: page)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.movies(query: query, page: page).path)
}
func testSearchMoviesWithYearAndPageReturnsMovies() async throws {
let query = String.randomString
let year = 2020
let expectedResult = MoviePageableList.mock()
let page = expectedResult.page
apiClient.result = .success(expectedResult)
let result = try await service.searchMovies(query: query, year: year, page: page)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.movies(query: query, year: year, page: page).path)
}
func testSearchTVShowsWithDefaultParametersReturnsTVShows() async throws {
let query = String.randomString
let expectedResult = TVShowPageableList.mock()
apiClient.result = .success(expectedResult)
let result = try await service.searchTVShows(query: query)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.tvShows(query: query).path)
}
func testSearchTVShowsReturnsTVShows() async throws {
let query = String.randomString
let expectedResult = TVShowPageableList.mock()
apiClient.result = .success(expectedResult)
let result = try await service.searchTVShows(query: query, firstAirDateYear: nil, page: nil)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.tvShows(query: query).path)
}
func testSearchTVShowsWithFirstAirDateYearReturnsTVShows() async throws {
let query = String.randomString
let year = 2020
let expectedResult = TVShowPageableList.mock()
apiClient.result = .success(expectedResult)
let result = try await service.searchTVShows(query: query, firstAirDateYear: year, page: nil)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.tvShows(query: query, firstAirDateYear: year).path)
}
func testSearchTVShowsWithPageReturnsTVShows() async throws {
let query = String.randomString
let expectedResult = TVShowPageableList.mock()
let page = expectedResult.page
apiClient.result = .success(expectedResult)
let result = try await service.searchTVShows(query: query, firstAirDateYear: nil, page: page)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.tvShows(query: query, page: page).path)
}
func testSearchTVShowsWithFirstAirDateYearANdPageReturnsTVShows() async throws {
let query = String.randomString
let year = 2020
let expectedResult = TVShowPageableList.mock()
let page = expectedResult.page
apiClient.result = .success(expectedResult)
let result = try await service.searchTVShows(query: query, firstAirDateYear: year, page: page)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath,
SearchEndpoint.tvShows(query: query, firstAirDateYear: year, page: page).path)
}
func testSearchPeopleWithDefaultParametersReturnsPeople() async throws {
let query = String.randomString
let expectedResult = PersonPageableList.mock()
apiClient.result = .success(expectedResult)
let result = try await service.searchPeople(query: query)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.people(query: query).path)
}
func testSearchPeopleReturnsPeople() async throws {
let query = String.randomString
let expectedResult = PersonPageableList.mock()
apiClient.result = .success(expectedResult)
let result = try await service.searchPeople(query: query, page: nil)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.people(query: query).path)
}
func testSearchPeopleWithPageReturnsPeople() async throws {
let query = String.randomString
let expectedResult = PersonPageableList.mock()
let page = expectedResult.page
apiClient.result = .success(expectedResult)
let result = try await service.searchPeople(query: query, page: page)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath, SearchEndpoint.people(query: query, page: page).path)
}
}
|
//
// PullingCarsModel.swift
// Bachelor project
//
// Created by Arthur Oleksiy on 4/17/18.
// Copyright © 2018 Arthur Oleksiy. All rights reserved.
//
import UIKit
class PullingCarsModel: NSObject {
}
|
//
// Simpson.swift
// SimpsonBook
//
// Created by Furkan Aykut on 4.09.2021.
//
import Foundation
import UIKit
class Simpson {
var name : String
var job : String
var image : UIImage
init(simpsonName:String,simpsonJob:String,simpsonImage:UIImage) {
name = simpsonName
job = simpsonJob
image = simpsonImage
}
}
|
//
// Groups.swift
// Joked
//
// Created by Jesse Frederick on 9/25/20.
// Copyright © 2020 Casanova Studios. All rights reserved.
//
import Foundation
import FirebaseDatabase
#warning("Group file set up for Firebase")
struct Group {
let id: UUID
let joke: String
let punchline: String
init(id: UUID = UUID(), joke: String, punchline: String) {
self.id = id
self.joke = joke
self.punchline = punchline
}
init?(snapshot: DataSnapshot) {
guard
let value = snapshot.value as? [String: AnyObject],
let joke = value["joke"] as? String,
let punchline = value["punchline"] as? String else {
return nil
}
self.id = UUID(uuidString: snapshot.key) ?? UUID()
self.joke = joke
self.punchline = punchline
}
func toDictionary() -> Any {
return [
"joke": joke,
"punchline": punchline
]
}
}
|
//
// FindViewModel.swift
// FLMusic
//
// Created by fengli on 2019/1/23.
// Copyright © 2019 冯里. All rights reserved.
//
import Foundation
import SwiftyJSON
import RxCocoa
import RxSwift
import YYCache
class FindViewModel: FLViewModelType{
var datas = [JSON]()
var next: String?
let cache = YYDiskCache(path: "\(PathManager.cachePath())/findDatas")
let refreshStatus = BehaviorRelay<FLRefreshStatus>(value: .none)
func transform(input: InputType?) -> OutputType? {
let input = input as! FinderInput
let new = input.headerRefresh.flatMapLatest { [unowned self] _ in
return self.requestData(false)
}
let more = input.footerRefresh.flatMapLatest { [unowned self] _ in
return self.requestData(true)
}
var cycleData = self.requestCycleData()
if let cacheData = self.getCycleCache() {
cycleData = cycleData.startWith(cacheData.arrayValue)
}
var musics = Driver.merge(new, more)
if let listCache = getListCache() {
self.datas = listCache["results"].arrayValue
let list = Driver.just(self.datas)
self.next = listCache["next"].string
musics = Driver.merge(list, musics)
}
return FindOutput(cycleData: cycleData, musics: musics, refreshStatus: refreshStatus.asDriver())
}
// 缓存轮播数据
func cacheCycle(data: JSON) {
let dataStr = data.rawString() as NSString?
if let dataStr = dataStr {
self.cache?.setObject(dataStr, forKey: "cycles")
}
}
// 获取轮播缓存数据
func getCycleCache() -> JSON?{
let cacheStr = self.cache?.object(forKey: "cycles")
if let cacheStr = cacheStr {
return JSON(parseJSON: cacheStr as! String)
}
return nil
}
// 请求轮播图数据
func requestCycleData() -> Driver<[JSON]>{
return NetworkManager.request(.recomment)
.do(onSuccess: { [unowned self] (data) in
self.cacheCycle(data: data)
})
.map({ (data) in
let results = data.arrayValue
return results
}).asDriver { (error) in
return Driver.empty()
}
}
// 缓存列表数据
func cacheList(data: JSON) {
let dataStr = data.rawString() as NSString?
if let dataStr = dataStr {
self.cache?.setObject(dataStr, forKey: "list")
}
}
// 获取列表缓存数据
func getListCache() -> JSON?{
let cacheStr = self.cache?.object(forKey: "list")
if let cacheStr = cacheStr {
return JSON(parseJSON: cacheStr as! String)
}
return nil
}
// 请求列表数据
func requestData(_ isMore: Bool) -> Driver<[JSON]> {
let next = isMore ? self.next : nil
return NetworkManager.request(.findList(next: next)).do(onSuccess: { [unowned self] data in
if !isMore {
self.cacheList(data: data)
}
}).map({ [unowned self] (data) in
let results = data["results"]
self.next = data["next"].string
let datas = results.arrayValue
if isMore {
self.datas.append(contentsOf: datas)
} else {
self.datas = datas
}
self.refreshStatus.accept(self.next == nil ? .noMoreData : .endRefresh)
return self.datas
}).asDriver(onErrorRecover: { [unowned self] (error) in
_ = FLToastView.show("加载失败")
self.refreshStatus.accept(.endRefresh)
return Driver.empty()
})
}
}
struct FindOutput: OutputType {
var cycleData: Driver<[JSON]>
var musics: Driver<[JSON]>
var refreshStatus: Driver<FLRefreshStatus>
}
|
//
// ParseLocalJSON.swift
// Weather Map
//
// Created by Yana on 14.09.2020.
//
import Foundation
class LocalJsonParser {
func getData() {
guard let mainUrl = Bundle.main.url(forResource: "countriesToCities", withExtension: "json") else { return }
decodeData(pathName: mainUrl)
}
func decodeData(pathName: URL) -> CityList?{
let decoder = JSONDecoder()
do{
let jsonData = try Data(contentsOf: pathName)
let cityListData = try decoder.decode(CityListData.self, from: jsonData)
guard let cityList = CityList(cityListData: cityListData) else {
return nil
}
return cityList
} catch let error as NSError {
print(error.localizedDescription)
}
return nil
}
}
|
//
// ViewController.swift
// PushNotification
//
// Created by Alex Lopez on 24/09/2019.
// Copyright © 2019 Alex Lopez. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
|
//
// FlickrImageDownloadManager.swift
// Virtual Tourist
//
// Created by Humberto Aquino on 4/21/15.
// Copyright (c) 2015 Humberto Aquino. All rights reserved.
//
import Foundation
import CoreLocation
import CoreData
// Sinfleton used to download images from Flickr and save them into Core Data
class FlickrImageDownloadManager: NSObject {
let httpClient = HTTPClient.sharedInstance()
// This operation queue is used to download the images using NSData to prevent
// Freezing the Main queue
let downloadQueue = NSOperationQueue()
lazy var sharedContext: NSManagedObjectContext! = {
return CoreDataStackManager.sharedInstance().managedObjectContext
}()
override init() {
super.init()
downloadQueue.maxConcurrentOperationCount = Queue.DownloadQueueMaxConcurrentOperationCount
}
// MARK: - Fetch methods
// Fetch a page of images for a pin location
func fetchInitialPhotosForPin(pin: Pin, completionHandler:((totalFetched: Int?, error: NSError?) -> Void)) {
// 1. Fetch photos of the location
let page = pin.currentPage + 1
let total = Pagination.TotalPhotosPerPage
let coordinate = pin.coordinate
// We get the JSON info to know what urls we need to download
fetchPhotosJSONForLocation(coordinate, fromPage: page, total: total) {
(json, error) in
if let error = error {
// Error during fetch
self.performOnMainQueue {
completionHandler(totalFetched: nil, error: error)
}
return
}
var jsonError: NSError? = nil
// 2. Parse the JSON to get photo urls
var result = self.parsePhotos(json!, error: &jsonError)
if let jsonError = jsonError {
self.performOnMainQueue {
completionHandler(totalFetched: nil, error: error)
}
return
}
// 3. Create 21 (or the amount fetched) entities of Photos with the url of the image and the state: New
let totalPhotos = result!.photoURLs.count
for url in result!.photoURLs {
let dictionary = [
Photo.Keys.ImageURL: url
]
let photo = Photo(dictionary: dictionary, context: CoreDataStackManager.sharedInstance().managedObjectContext!)
photo.pin = pin
}
// 4. Save the page number and the pages total in the Pin
let totalPages = result!.pages
if page >= totalPages {
pin.currentPage = Pin.InitialPageNumber
} else {
pin.currentPage = page
}
pin.totalPages = result!.pages
// 5. Save on main queue
self.performOnMainQueue {
pin.pendingDownloads = totalPhotos
CoreDataStackManager.sharedInstance().saveContext()
// The Photos are created and associated with the pin.
// Call the caller to let them know that we know how much photos
// we need to download
completionHandler(totalFetched: totalPhotos, error: nil)
// 6. Start the download of the images, if necesary
self.downloadPinImages(pin)
}
}
}
// Do a paginated search of images using coordinate. The result is the JSON unalterated
func fetchPhotosJSONForLocation(coordinate: CLLocationCoordinate2D, fromPage page: Int, total: Int, completionHandler:((json: NSDictionary?, error: NSError?) -> Void)) {
let parameters = locationImagePaginatedSearch(coordinate, page: page, perPage: total)
httpClient.jsonTaskForGETMethod(URLs.BaseURL, parameters: parameters) { (jsonResponse, response, error) -> Void in
if let error = error {
// Error in the GET request
completionHandler(json: nil, error: error)
return
}
// Success
completionHandler(json: jsonResponse, error: nil)
}
}
// MARK: - Downloading
// Initiates the download of all the photos of the pin parameter
func downloadPinImages(pin: Pin) {
if let photos = pin.photos {
if photos.count > 0 {
downloadQueue.addOperationWithBlock {
for photo in photos {
self.downloadAndSavePhoto(photo)
}
}
return
}
}
println("Pin does not have photos")
}
// Download a single photo and save it's data when done
// This method should be performed on the download Queue
func downloadAndSavePhoto(photo: Photo) {
// Do it in another queue
if photo.imageState == Photo.State.Ready {
println("Image ready")
return
}
if let url = NSURL(string: photo.imageURL!) {
let timestamp = NSDate().timestampIntervalInMilliseconsSince1970()
let postfixFilename = obtainPhotoFilename(url)
let filename = "\(timestamp)_\(postfixFilename)"
println("Downloading image: \(filename)")
if let imageData = NSData(contentsOfURL: url) {
let imagePath = CoreDataStackManager.sharedInstance().pathForfilename(filename)!
if imageData.writeToFile(imagePath, atomically: true) {
photo.imageFilename = filename
photo.imageState = Photo.State.Ready
self.performOnMainQueue {
if let pin = photo.pin {
pin.decreasePendingDownloads()
} else {
println("Photo downloaded without a pin")
abort()
}
// Save photo and pin count
CoreDataStackManager.sharedInstance().saveContext()
println("Saved: \(filename)")
}
} else {
// Could not save file
println("Could not save image to: \(imagePath)")
}
} else {
println("Could not download image: \(url)")
}
} else {
println("No valid url to download: \(photo.imageURL!)")
}
}
// MARK: - Utilities
func obtainPhotoFilename(photoURL: NSURL) -> String {
let components = photoURL.pathComponents as! [String]
return components.last!
}
// MARK: - Shared instance
class func sharedInstance() -> FlickrImageDownloadManager {
struct Static {
static let instance = FlickrImageDownloadManager()
}
return Static.instance
}
}
// MARK: - JSON utilities
extension FlickrImageDownloadManager {
// Based on the search result, navigate the JSON and get the list of URLs to download
// and the amount of pages according to Flickr
func parsePhotos(json: NSDictionary, inout error: NSError?) -> (photoURLs:[String], pages: Int)? {
if let photoInfo = json[ResponseKeys.Photos] as? NSDictionary {
if let pages = photoInfo[ParameterValues.Pages] as? Int {
if let photoList = photoInfo[ResponseKeys.Photo] as? NSArray {
var result:[String] = [String]()
for item in photoList {
if let url = item[ParameterValues.URLM] as? String {
result.append(url)
}
}
return (result, pages)
}
}
}
error = ErrorUtils.errorForJSONInterpreting(json)
return nil
}
}
|
//
// WorkingHoursCell.swift
// MyApp2
//
// Created by Anıl Demirci on 8.07.2021.
//
import UIKit
class WorkingHoursCell: UITableViewCell {
@IBOutlet weak var dayLabel: UILabel!
@IBOutlet weak var deleteView: UIImageView!
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
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.