repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tuanphung/ATTableView | Demo/Demo/TableViewCells/HotelTableViewCell.swift | 2 | 2229 | //
// Copyright (c) 2016 PHUNG ANH TUAN. 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 UIKit
import ATTableView
import HCSStarRatingView
class HotelTableViewCell: UITableViewCell {
// MARK: - IBOutlets
@IBOutlet weak var topImageView: UIImageView!
@IBOutlet weak var ratingPointLabel: UILabel!
@IBOutlet weak var ratingTextLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var starRatingView: HCSStarRatingView!
@IBOutlet weak var priceLabel: UILabel!
override func prepareForReuse() {
super.prepareForReuse()
self.selectionStyle = .None
}
}
// MARK: TableViewCell Configurations
extension HotelTableViewCell: ATTableViewCellProtocol {
typealias ModelType = Hotel
static func height(hotel: ModelType) -> CGFloat {
return 250
}
func configureCell(hotel: ModelType) {
self.titleLabel.text = hotel.name
self.topImageView.image = UIImage(named: hotel.imageName)
self.starRatingView.value = CGFloat(hotel.rating)
self.ratingPointLabel.text = "\(hotel.userRating)"
self.priceLabel.text = "\(hotel.price) $"
}
} | mit | f160fbcd9e990ea3f90d98e7cfb63866 | 38.122807 | 80 | 0.729475 | 4.66318 | false | false | false | false |
madbat/SwiftMath | SwiftMathTests/Vector3Tests.swift | 1 | 2280 | //
// VectorR3Tests.swift
// SwiftMath
//
// Created by Matteo Battaglio on 31/05/15.
// Copyright (c) 2015 GlidingSwift. All rights reserved.
//
import Foundation
import SwiftMath
import Quick
import Nimble
class Vector3Spec: QuickSpec {
override func spec() {
let v1 = Vector3(x: 1, y: 2, z: 3)
let v2 = Vector3(x: 5, y: 6, z: 7)
let v3 = Vector3(x: -20, y: 0, z: -5)
describe("addition") {
it("sums each component of one vector to the corresponding component of the other vector") {
expect(v1 + v2).to(equal(Vector3(x: v1.x + v2.x, y: v1.y + v2.y, z: v1.z + v2.z)))
}
it("is commutative") {
expect(v1 + v2).to(equal(v2 + v1))
}
it("is associative") {
expect(v1 + (v2 + v3)).to(equal((v1 + v2) + v3))
}
it("has an identity element: the zero vector") {
expect(v1 + .zero()).to(equal(v1))
}
}
describe("subtraction") {
it("subtracts each component of one vector from the corresponding component of the other vector") {
expect(v1 - v2).to(equal(Vector3(x: v1.x - v2.x, y: v1.y - v2.y, z: v1.z - v2.z)))
}
}
describe("multiplication") {
it("is associative") {
expect(3 * (2 * v1)).to(equal((3 * 2) * v1))
}
it("is distributive") {
var expected = (5 * v1) + (5 * v2)
expect(5 * (v1 + v2)).to(equal(expected))
expected = (5 * v1) + (6 * v1)
expect((5 + 6) * v1).to(equal(expected))
}
}
describe("rotation") {
it("rotates a vector as expected") {
let original = Vector3(x: 3, y: 4, z: 0)
let rotation = Quaternion(axis: Vector3(x: 1, y: 0, z: 0), angle: Double.PI/2.0)
let result = original.rotate(rotation)
let expected = Vector3(x: 3, y: 0, z: 4.0)
expect(result).to(beCloseTo(expected))
expect(result.length).to(equal(original.length))
}
}
}
} | mit | 7746566f1f98ed7c14e0c837b4200a00 | 32.057971 | 111 | 0.466228 | 3.47561 | false | false | false | false |
HackerEcology/BeginnerCourse | tdjackey/GuidedTour.playground/section-58.swift | 2 | 680 | class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triangle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
println(triangle.perimeter)
triangle.perimeter = 9.9
println(triangle.sideLength)
| mit | ffd4d3679b6ea7797c1b4c038e0063ac | 25.153846 | 76 | 0.608824 | 4.473684 | false | false | false | false |
emericspiroux/Open42 | correct42/Controllers/SettingsViewController.swift | 1 | 1636 | //
// SettingsViewController.swift
// Open42
//
// Created by larry on 07/09/2016.
// Copyright © 2016 42. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: - Proprieties
var cursus:[Cursus] = []
var selectedCursus:Cursus?
// MARK: - IBOutlets
/// Table view
@IBOutlet weak var tableView: UITableView!
// MARK: - View life cycle
/// Delegate table view
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
}
// MARK: - TableView delegation
/**
Count `projects` for the `tableView` numberOfRowsInSection.
*/
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cursus.count
}
/**
Create a `UITableViewCell` and fill it.
- Returns: `UITableViewCell` text filled.
*/
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = cursus[indexPath.row].name
return (cell)
}
/// Select cursus in `UserManager.selectedCursus`, clean the project list and go back in navigation view.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//Select Cursus and dissmiss view after displaying alert with cursus set.
UserManager.Shared().selectedCursus = cursus[indexPath.row]
ProjectsManager.Shared().cleanList()
if let nav = self.navigationController {
nav.popViewControllerAnimated(true)
}
}
}
| apache-2.0 | 57f44f77e46eb98a66f13307383a3857 | 27.189655 | 106 | 0.727829 | 4.097744 | false | false | false | false |
ikesyo/swift-corelibs-foundation | Foundation/URLSession/NativeProtocol.swift | 4 | 24325 | // Foundation/URLSession/NativeProtocol.swift - NSURLSession & libcurl
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
///
/// This file has the common implementation of Native protocols like HTTP,FTP,Data
/// These are libcurl helpers for the URLSession API code.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/
/// - SeeAlso: NSURLSession.swift
///
// -----------------------------------------------------------------------------
import CoreFoundation
import Dispatch
internal let enableLibcurlDebugOutput: Bool = {
return ProcessInfo.processInfo.environment["URLSessionDebugLibcurl"] != nil
}()
internal let enableDebugOutput: Bool = {
return ProcessInfo.processInfo.environment["URLSessionDebug"] != nil
}()
internal class _NativeProtocol: URLProtocol, _EasyHandleDelegate {
internal var easyHandle: _EasyHandle!
internal lazy var tempFileURL: URL = {
let fileName = NSTemporaryDirectory() + NSUUID().uuidString + ".tmp"
_ = FileManager.default.createFile(atPath: fileName, contents: nil)
return URL(fileURLWithPath: fileName)
}()
public required init(task: URLSessionTask, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) {
self.internalState = _InternalState.initial
super.init(request: task.originalRequest!, cachedResponse: cachedResponse, client: client)
self.task = task
self.easyHandle = _EasyHandle(delegate: self)
}
public required init(request: URLRequest, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) {
self.internalState = _InternalState.initial
super.init(request: request, cachedResponse: cachedResponse, client: client)
self.easyHandle = _EasyHandle(delegate: self)
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override func startLoading() {
resume()
}
override func stopLoading() {
if task?.state == .suspended {
suspend()
} else {
self.internalState = .transferFailed
guard let error = self.task?.error else { fatalError() }
completeTask(withError: error)
}
}
var internalState: _InternalState {
// We manage adding / removing the easy handle and pausing / unpausing
// here at a centralized place to make sure the internal state always
// matches up with the state of the easy handle being added and paused.
willSet {
if !internalState.isEasyHandlePaused && newValue.isEasyHandlePaused {
fatalError("Need to solve pausing receive.")
}
if internalState.isEasyHandleAddedToMultiHandle && !newValue.isEasyHandleAddedToMultiHandle {
task?.session.remove(handle: easyHandle)
}
}
didSet {
if !oldValue.isEasyHandleAddedToMultiHandle && internalState.isEasyHandleAddedToMultiHandle {
task?.session.add(handle: easyHandle)
}
if oldValue.isEasyHandlePaused && !internalState.isEasyHandlePaused {
fatalError("Need to solve pausing receive.")
}
}
}
func didReceive(data: Data) -> _EasyHandle._Action {
guard case .transferInProgress(var ts) = internalState else {
fatalError("Received body data, but no transfer in progress.")
}
if let response = validateHeaderComplete(transferState:ts) {
ts.response = response
}
notifyDelegate(aboutReceivedData: data)
internalState = .transferInProgress(ts.byAppending(bodyData: data))
return .proceed
}
func validateHeaderComplete(transferState: _TransferState) -> URLResponse? {
guard transferState.isHeaderComplete else {
fatalError("Received body data, but the header is not complete, yet.")
}
return nil
}
fileprivate func notifyDelegate(aboutReceivedData data: Data) {
guard let t = self.task else {
fatalError("Cannot notify")
}
if case .taskDelegate(let delegate) = t.session.behaviour(for: self.task!),
let dataDelegate = delegate as? URLSessionDataDelegate,
let task = self.task as? URLSessionDataTask {
// Forward to the delegate:
guard let s = self.task?.session as? URLSession else {
fatalError()
}
s.delegateQueue.addOperation {
dataDelegate.urlSession(s, dataTask: task, didReceive: data)
}
} else if case .taskDelegate(let delegate) = t.session.behaviour(for: self.task!),
let downloadDelegate = delegate as? URLSessionDownloadDelegate,
let task = self.task as? URLSessionDownloadTask {
guard let s = self.task?.session as? URLSession else {
fatalError()
}
let fileHandle = try! FileHandle(forWritingTo: self.tempFileURL)
_ = fileHandle.seekToEndOfFile()
fileHandle.write(data)
task.countOfBytesReceived += Int64(data.count)
s.delegateQueue.addOperation {
downloadDelegate.urlSession(s, downloadTask: task, didWriteData: Int64(data.count), totalBytesWritten: task.countOfBytesReceived,
totalBytesExpectedToWrite: task.countOfBytesExpectedToReceive)
}
if task.countOfBytesExpectedToReceive == task.countOfBytesReceived {
fileHandle.closeFile()
self.properties[.temporaryFileURL] = self.tempFileURL
}
}
}
fileprivate func notifyDelegate(aboutUploadedData count: Int64) {
guard let task = self.task as? URLSessionUploadTask,
let session = self.task?.session as? URLSession,
case .taskDelegate(let delegate) = session.behaviour(for: task) else { return }
task.countOfBytesSent += count
session.delegateQueue.addOperation {
delegate.urlSession(session, task: task, didSendBodyData: count,
totalBytesSent: task.countOfBytesSent, totalBytesExpectedToSend: task.countOfBytesExpectedToSend)
}
}
func didReceive(headerData data: Data, contentLength: Int64) -> _EasyHandle._Action {
NSRequiresConcreteImplementation()
}
func fill(writeBuffer buffer: UnsafeMutableBufferPointer<Int8>) -> _EasyHandle._WriteBufferResult {
guard case .transferInProgress(let ts) = internalState else {
fatalError("Requested to fill write buffer, but transfer isn't in progress.")
}
guard let source = ts.requestBodySource else {
fatalError("Requested to fill write buffer, but transfer state has no body source.")
}
switch source.getNextChunk(withLength: buffer.count) {
case .data(let data):
copyDispatchData(data, infoBuffer: buffer)
let count = data.count
assert(count > 0)
notifyDelegate(aboutUploadedData: Int64(count))
return .bytes(count)
case .done:
return .bytes(0)
case .retryLater:
// At this point we'll try to pause the easy handle. The body source
// is responsible for un-pausing the handle once data becomes
// available.
return .pause
case .error:
return .abort
}
}
func transferCompleted(withError error: NSError?) {
// At this point the transfer is complete and we can decide what to do.
// If everything went well, we will simply forward the resulting data
// to the delegate. But in case of redirects etc. we might send another
// request.
guard case .transferInProgress(let ts) = internalState else {
fatalError("Transfer completed, but it wasn't in progress.")
}
guard let request = task?.currentRequest else {
fatalError("Transfer completed, but there's no current request.")
}
guard error == nil else {
internalState = .transferFailed
failWith(error: error!, request: request)
return
}
if let response = task?.response {
var transferState = ts
transferState.response = response
}
guard let response = ts.response else {
fatalError("Transfer completed, but there's no response.")
}
internalState = .transferCompleted(response: response, bodyDataDrain: ts.bodyDataDrain)
let action = completionAction(forCompletedRequest: request, response: response)
switch action {
case .completeTask:
completeTask()
case .failWithError(let errorCode):
internalState = .transferFailed
let error = NSError(domain: NSURLErrorDomain, code: errorCode,
userInfo: [NSLocalizedDescriptionKey: "Completion failure"])
failWith(error: error, request: request)
case .redirectWithRequest(let newRequest):
redirectFor(request: newRequest)
}
}
func redirectFor(request: URLRequest) {
NSRequiresConcreteImplementation()
}
func completeTask() {
guard case .transferCompleted(response: let response, bodyDataDrain: let bodyDataDrain) = self.internalState else {
fatalError("Trying to complete the task, but its transfer isn't complete.")
}
task?.response = response
// We don't want a timeout to be triggered after this. The timeout timer needs to be cancelled.
easyHandle.timeoutTimer = nil
// because we deregister the task with the session on internalState being set to taskCompleted
// we need to do the latter after the delegate/handler was notified/invoked
if case .inMemory(let bodyData) = bodyDataDrain {
var data = Data()
if let body = bodyData {
data = Data(bytes: body.bytes, count: body.length)
}
self.client?.urlProtocol(self, didLoad: data)
self.internalState = .taskCompleted
}
if case .toFile(let url, let fileHandle?) = bodyDataDrain {
self.properties[.temporaryFileURL] = url
fileHandle.closeFile()
}
self.client?.urlProtocolDidFinishLoading(self)
self.internalState = .taskCompleted
}
func completionAction(forCompletedRequest request: URLRequest, response: URLResponse) -> _CompletionAction {
return .completeTask
}
func seekInputStream(to position: UInt64) throws {
// We will reset the body source and seek forward.
NSUnimplemented()
}
func updateProgressMeter(with propgress: _EasyHandle._Progress) {
//TODO: Update progress. Note that a single URLSessionTask might
// perform multiple transfers. The values in `progress` are only for
// the current transfer.
}
/// The data drain.
///
/// This depends on what the delegate / completion handler need.
fileprivate func createTransferBodyDataDrain() -> _DataDrain {
guard let task = task else {
fatalError()
}
let s = task.session as! URLSession
switch s.behaviour(for: task) {
case .noDelegate:
return .ignore
case .taskDelegate:
// Data will be forwarded to the delegate as we receive it, we don't
// need to do anything about it.
return .ignore
case .dataCompletionHandler:
// Data needs to be concatenated in-memory such that we can pass it
// to the completion handler upon completion.
return .inMemory(nil)
case .downloadCompletionHandler:
// Data needs to be written to a file (i.e. a download task).
let fileHandle = try! FileHandle(forWritingTo: self.tempFileURL)
return .toFile(self.tempFileURL, fileHandle)
}
}
func createTransferState(url: URL, workQueue: DispatchQueue) -> _TransferState {
let drain = createTransferBodyDataDrain()
guard let t = task else {
fatalError("Cannot create transfer state")
}
switch t.body {
case .none:
return _TransferState(url: url, bodyDataDrain: drain)
case .data(let data):
let source = _BodyDataSource(data: data)
return _TransferState(url: url, bodyDataDrain: drain,bodySource: source)
case .file(let fileURL):
let source = _BodyFileSource(fileURL: fileURL, workQueue: workQueue, dataAvailableHandler: { [weak self] in
// Unpause the easy handle
self?.easyHandle.unpauseSend()
})
return _TransferState(url: url, bodyDataDrain: drain,bodySource: source)
case .stream:
NSUnimplemented()
}
}
/// Start a new transfer
func startNewTransfer(with request: URLRequest) {
guard let t = task else {
fatalError()
}
t.currentRequest = request
guard let url = request.url else {
fatalError("No URL in request.")
}
self.internalState = .transferReady(createTransferState(url: url, workQueue: t.workQueue))
configureEasyHandle(for: request)
if (t.suspendCount) < 1 {
resume()
}
}
func resume() {
if case .initial = self.internalState {
guard let r = task?.originalRequest else {
fatalError("Task has no original request.")
}
startNewTransfer(with: r)
}
if case .transferReady(let transferState) = self.internalState {
self.internalState = .transferInProgress(transferState)
}
}
func suspend() {
if case .transferInProgress(let transferState) = self.internalState {
self.internalState = .transferReady(transferState)
}
}
func configureEasyHandle(for: URLRequest) {
NSRequiresConcreteImplementation()
}
}
extension _NativeProtocol {
/// Action to be taken after a transfer completes
enum _CompletionAction {
case completeTask
case failWithError(Int)
case redirectWithRequest(URLRequest)
}
func completeTask(withError error: Error) {
task?.error = error
guard case .transferFailed = self.internalState else {
fatalError("Trying to complete the task, but its transfer isn't complete / failed.")
}
//We don't want a timeout to be triggered after this. The timeout timer needs to be cancelled.
easyHandle.timeoutTimer = nil
self.internalState = .taskCompleted
}
func failWith(error: NSError, request: URLRequest) {
//TODO: Error handling
let userInfo: [String : Any]? = request.url.map {
[
NSUnderlyingErrorKey: error,
NSURLErrorFailingURLErrorKey: $0,
NSURLErrorFailingURLStringErrorKey: $0.absoluteString,
NSLocalizedDescriptionKey: NSLocalizedString(error.localizedDescription, comment: "N/A")
]
}
let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: error.code, userInfo: userInfo))
completeTask(withError: urlError)
self.client?.urlProtocol(self, didFailWithError: urlError)
}
/// Give the delegate a chance to tell us how to proceed once we have a
/// response / complete header.
///
/// This will pause the transfer.
func askDelegateHowToProceedAfterCompleteResponse(_ response: URLResponse, delegate: URLSessionDataDelegate) {
// Ask the delegate how to proceed.
// This will pause the easy handle. We need to wait for the
// delegate before processing any more data.
guard case .transferInProgress(let ts) = self.internalState else {
fatalError("Transfer not in progress.")
}
self.internalState = .waitingForResponseCompletionHandler(ts)
let dt = task as! URLSessionDataTask
// We need this ugly cast in order to be able to support `URLSessionTask.init()`
guard let s = task?.session as? URLSession else {
fatalError()
}
s.delegateQueue.addOperation {
delegate.urlSession(s, dataTask: dt, didReceive: response, completionHandler: { [weak self] disposition in
guard let task = self else { return }
self?.task?.workQueue.async {
task.didCompleteResponseCallback(disposition: disposition)
}
})
}
}
/// This gets called (indirectly) when the data task delegates lets us know
/// how we should proceed after receiving a response (i.e. complete header).
func didCompleteResponseCallback(disposition: URLSession.ResponseDisposition) {
guard case .waitingForResponseCompletionHandler(let ts) = self.internalState else {
fatalError("Received response disposition, but we're not waiting for it.")
}
switch disposition {
case .cancel:
let error = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled))
self.completeTask(withError: error)
self.client?.urlProtocol(self, didFailWithError: error)
case .allow:
// Continue the transfer. This will unpause the easy handle.
self.internalState = .transferInProgress(ts)
case .becomeDownload:
/* Turn this request into a download */
NSUnimplemented()
case .becomeStream:
/* Turn this task into a stream task */
NSUnimplemented()
}
}
}
extension _NativeProtocol {
enum _InternalState {
/// Task has been created, but nothing has been done, yet
case initial
/// The easy handle has been fully configured. But it is not added to
/// the multi handle.
case transferReady(_TransferState)
/// The easy handle is currently added to the multi handle
case transferInProgress(_TransferState)
/// The transfer completed.
///
/// The easy handle has been removed from the multi handle. This does
/// not necessarily mean the task completed. A task that gets
/// redirected will do multiple transfers.
case transferCompleted(response: URLResponse, bodyDataDrain: _NativeProtocol._DataDrain)
/// The transfer failed.
///
/// Same as `.transferCompleted`, but without response / body data
case transferFailed
/// Waiting for the completion handler of the HTTP redirect callback.
///
/// When we tell the delegate that we're about to perform an HTTP
/// redirect, we need to wait for the delegate to let us know what
/// action to take.
case waitingForRedirectCompletionHandler(response: URLResponse, bodyDataDrain: _NativeProtocol._DataDrain)
/// Waiting for the completion handler of the 'did receive response' callback.
///
/// When we tell the delegate that we received a response (i.e. when
/// we received a complete header), we need to wait for the delegate to
/// let us know what action to take. In this state the easy handle is
/// paused in order to suspend delegate callbacks.
case waitingForResponseCompletionHandler(_TransferState)
/// The task is completed
///
/// Contrast this with `.transferCompleted`.
case taskCompleted
}
}
extension _NativeProtocol._InternalState {
var isEasyHandleAddedToMultiHandle: Bool {
switch self {
case .initial: return false
case .transferReady: return false
case .transferInProgress: return true
case .transferCompleted: return false
case .transferFailed: return false
case .waitingForRedirectCompletionHandler: return false
case .waitingForResponseCompletionHandler: return true
case .taskCompleted: return false
}
}
var isEasyHandlePaused: Bool {
switch self {
case .initial: return false
case .transferReady: return false
case .transferInProgress: return false
case .transferCompleted: return false
case .transferFailed: return false
case .waitingForRedirectCompletionHandler: return false
case .waitingForResponseCompletionHandler: return true
case .taskCompleted: return false
}
}
}
extension _NativeProtocol {
enum _Error: Error {
case parseSingleLineError
case parseCompleteHeaderError
}
func errorCode(fileSystemError error: Error) -> Int {
func fromCocoaErrorCode(_ code: Int) -> Int {
switch code {
case CocoaError.fileReadNoSuchFile.rawValue:
return NSURLErrorFileDoesNotExist
case CocoaError.fileReadNoPermission.rawValue:
return NSURLErrorNoPermissionsToReadFile
default:
return NSURLErrorUnknown
}
}
switch error {
case let e as NSError where e.domain == NSCocoaErrorDomain:
return fromCocoaErrorCode(e.code)
default:
return NSURLErrorUnknown
}
}
}
extension _NativeProtocol._ResponseHeaderLines {
func createURLResponse(for URL: URL, contentLength: Int64) -> URLResponse? {
return URLResponse(url: URL, mimeType: nil, expectedContentLength: Int(contentLength), textEncodingName: nil)
}
}
internal extension _NativeProtocol {
enum _Body {
case none
case data(DispatchData)
/// Body data is read from the given file URL
case file(URL)
case stream(InputStream)
}
}
fileprivate extension _NativeProtocol._Body {
enum _Error : Error {
case fileForBodyDataNotFound
}
/// - Returns: The body length, or `nil` for no body (e.g. `GET` request).
func getBodyLength() throws -> UInt64? {
switch self {
case .none:
return 0
case .data(let d):
return UInt64(d.count)
/// Body data is read from the given file URL
case .file(let fileURL):
guard let s = try FileManager.default.attributesOfItem(atPath: fileURL.path)[.size] as? NSNumber else {
throw _Error.fileForBodyDataNotFound
}
return s.uint64Value
case .stream:
return nil
}
}
}
extension _NativeProtocol {
/// Set request body length.
///
/// An unknown length
func set(requestBodyLength length: _HTTPURLProtocol._RequestBodyLength) {
switch length {
case .noBody:
easyHandle.set(upload: false)
easyHandle.set(requestBodyLength: 0)
case .length(let length):
easyHandle.set(upload: true)
easyHandle.set(requestBodyLength: Int64(length))
case .unknown:
easyHandle.set(upload: true)
easyHandle.set(requestBodyLength: -1)
}
}
enum _RequestBodyLength {
case noBody
///
case length(UInt64)
/// Will result in a chunked upload
case unknown
}
}
extension URLSession {
static func printDebug(_ text: @autoclosure () -> String) {
guard enableDebugOutput else { return }
debugPrint(text())
}
}
| apache-2.0 | 91fc395ef291a74d745c4df84aa8ac33 | 38.552846 | 145 | 0.619116 | 5.362654 | false | false | false | false |
britez/sdk-ios | sdk_ios_v2/Classes/sdk/APIs/PaymentsTokenAPI.swift | 1 | 2651 | //
// PaymentsTokenAPI.swift
//
//
import Alamofire
open class PaymentsTokenAPI: APIBase {
static let PATH = "/tokens"
var publicKey: String
var isSandbox: Bool
public init(publicKey: String, isSandbox: Bool = false) {
self.publicKey = publicKey
self.isSandbox = isSandbox
}
open static var publicKey:String?
/**
Creates a new payment token
- parameter paymentTokenInfo: (body) (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
open func createPaymentToken(paymentTokenInfo: PaymentTokenInfo? = nil, completion: @escaping ((_ data: PaymentToken?,_ error: Error?) -> Void)) {
self.tokensPostWithRequestBuilder(paymentTokenInfo: paymentTokenInfo).execute { (response, error) -> Void in
completion(response?.body, error);
}
}
open func createPaymentTokenWithCardToken(paymentTokenInfoWithCardToken: PaymentTokenInfoWithCardToken? = nil, completion: @escaping ((_ data: PaymentToken?,_ error: Error?) -> Void)) {
self.tokensPostWithCardTokenRequestBuilder(paymentTokenInfoWithCardToken: paymentTokenInfoWithCardToken).execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
- parameter paymentTokenInfo: (body) (optional)
- returns: RequestBuilder<PaymentToken>
*/
open func tokensPostWithRequestBuilder(paymentTokenInfo: PaymentTokenInfo? = nil) -> RequestBuilder<PaymentToken> {
let parameters = paymentTokenInfo?.encodeToJSON() as? [String:AnyObject]
return proceedPayment(parameters: parameters)
}
open func tokensPostWithCardTokenRequestBuilder(paymentTokenInfoWithCardToken: PaymentTokenInfoWithCardToken? = nil) -> RequestBuilder<PaymentToken> {
let parameters = paymentTokenInfoWithCardToken?.encodeToJSON() as? [String:AnyObject]
return proceedPayment(parameters: parameters)
}
open func proceedPayment(parameters: [String:AnyObject]? = nil) -> RequestBuilder<PaymentToken> {
let URLString = DecClientAPI.getBasePath(isSandbox: self.isSandbox) + PaymentsTokenAPI.PATH
let url = NSURLComponents(string: URLString)
let requestBuilder: RequestBuilder<PaymentToken>.Type = DecClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true, headers: ["apikey": self.publicKey])
}
}
| mit | 516080c1b2a49c3bbe1acc755f1eb7fb | 33.881579 | 189 | 0.67748 | 5.167641 | false | false | false | false |
elpassion/el-space-ios | ELSpaceTests/TestCases/Commons/SelectionScreenPresenterSpec.swift | 1 | 1813 | import Quick
import Nimble
@testable import ELSpace
class SelectionScreenPresenterSpec: QuickSpec {
override func spec() {
describe("SelectionScreenPresenter") {
var sut: SelectionScreenPresenter!
var activitiesCoordinatorFactoryMock: ActivitiesCoordinatorFactoryMock!
var viewControllerPresenterSpy: ViewControllerPresenterSpy!
var viewControllerFake: UIViewController!
beforeEach {
activitiesCoordinatorFactoryMock = ActivitiesCoordinatorFactoryMock()
viewControllerPresenterSpy = ViewControllerPresenterSpy()
viewControllerFake = UIViewController()
sut = SelectionScreenPresenter(activitiesCoordinatorFactory: activitiesCoordinatorFactoryMock,
viewControllerPresenter: viewControllerPresenterSpy,
presenterViewController: viewControllerFake)
}
afterEach {
activitiesCoordinatorFactoryMock = nil
viewControllerPresenterSpy = nil
viewControllerFake = nil
sut = nil
}
context("when present hub") {
beforeEach {
sut.presentHub()
}
it("should present hub on correct view controller") {
expect(viewControllerPresenterSpy.presenter).to(equal(viewControllerFake))
}
it("should present correct view controller") {
expect(viewControllerPresenterSpy.pushedViewController)
.to(equal(activitiesCoordinatorFactoryMock.fakeCoordinator.initialViewController))
}
}
}
}
}
| gpl-3.0 | 80fd63a5d63ea8f20ce2e85ce902e8ba | 36 | 110 | 0.592388 | 7.166008 | false | false | false | false |
AlexandreCassagne/RuffLife-iOS | RuffLife/FoundViewController.swift | 1 | 6203 | //
// FoundViewController.swift
// RuffLife
//
// Created by Alexandre Cassagne on 21/10/2017.
// Copyright © 2017 Cassagne. All rights reserved.
//
import UIKit
import AWSDynamoDB
import CoreLocation
class FoundViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate {
var locationCoordinate: CLLocationCoordinate2D?
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let l = locations[0]
locationCoordinate = l.coordinate
location.text = "\(locationCoordinate!.latitude, locationCoordinate!.latitude)"
}
var url: String?
var uploadImage: UploadImage?
var imagePicker = UIImagePickerController()
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
private func startAzure() {
let a = Azure()
print("Starting azure...")
a.request(url: self.url!) { predictions in
print("Got callback.")
let top = predictions[0] as! [String: Any]
print(top)
let p = top["Probability"] as! Double
let breed = top["Tag"] as! String
if (p > 0.08) {
OperationQueue.main.addOperation({
self.breed.text = breed
})
}
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
pictureView.image = image
uploadImage = UploadImage(image: image)
print("Starting upload...")
uploadImage?.post {
print("Returned: \(self.uploadImage?.publicURL)")
self.url = self.uploadImage?.publicURL?.absoluteString
self.startAzure()
}
picker.dismiss(animated: true, completion: nil)
}
@IBOutlet weak var location: UITextField!
@IBOutlet weak var breed: UITextField!
// @IBOutlet weak var color: UITextField!
@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var number: UITextField!
@IBOutlet weak var pictureView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
// Do any additional setup after loading the view.
}
@IBAction func submit(_ sender: Any) {
guard let coordinate = self.locationCoordinate, let name = firstName.text, let phoneNumber = number.text else {
let alert = UIAlertController(title: "Incomplete Form", message: "Please ensure the form is completely filled out before proceeding.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
let db = AWSDynamoDBObjectMapper.default()
let newPet = RuffLife()!
newPet.FirstName = name
// newPet.LastName = "Empty"
newPet.PhoneNumber = phoneNumber
newPet.Breed = breed.text
// newPet.Color = color.text
newPet.ImageURL = url!
newPet.lat = coordinate.latitude as NSNumber
newPet.lon = coordinate.longitude as NSNumber
newPet.PetID = NSNumber(integerLiteral: Int(arc4random()))
db.save(newPet).continueWith(block: { (task:AWSTask<AnyObject>!) -> Any? in
DispatchQueue.main.async {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
if let error = task.error as NSError? {
alert.title = "Failure"
alert.message = "The request failed. Error: \(error)"
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
} else {
// Do something with task.result or perform other operations.
alert.title = "Success"
alert.message = "Successfully published to location of this pet!"
alert.addAction(UIAlertAction(title: "Done", style: .default, handler: { _ in
self.navigationController!.popViewController(animated: true)
}))
self.present(alert, animated: true, completion: nil)
}
}
return nil
})
}
func openCamera()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera))
{
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
else
{
let alert = UIAlertController(title: "Warning", message: "You don't have a camera", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func openGallary()
{
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
@IBAction func autofill(_ sender: Any) {
let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
self.openCamera()
}))
alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in
self.openGallary()
}))
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.startUpdatingLocation()
self.present(alert, animated: true, completion: nil)
// self.show(picker, sender: self)
present(imagePicker, animated: true, completion: nil)
}
let locationManager = CLLocationManager()
@IBOutlet weak var autofill: UIButton!
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.
}
*/
}
| mit | 33337430c0982c7a5dbbd5867ef251d5 | 32.344086 | 161 | 0.722025 | 4.110007 | false | false | false | false |
nodes-vapor/admin-panel-provider | Sources/AdminPanelProvider/Tags/Leaf/ColorGroup.swift | 1 | 1649 | import Leaf
import Vapor
public final class ColorGroup: BasicTag {
public init(){}
public let name = "form:colorgroup"
public func run(arguments: ArgumentList) throws -> Node? {
guard
arguments.count >= 2,
case .variable(let fieldsetPathNodes, value: let fieldset) = arguments.list[0],
let fieldsetPath = fieldsetPathNodes.last
else {
throw Abort(.internalServerError, reason: "FormDateGroup parse error, expecting: #form:dategroup(\"name\", \"default\", fieldset)")
}
// Retrieve input value, value from fieldset else passed default value
let inputValue = fieldset?["value"]?.string ?? arguments[1]?.string ?? ""
let label = fieldset?["label"]?.string
let errors = fieldset?["errors"]?.array
let hasErrors = !(errors?.isEmpty ?? true)
var template: [String] = [
"<div class=\"form-group action-wrapper\(hasErrors ? " has-error" : "")\">",
"<div id=\"\(fieldsetPath)-cp\" class=\"input-group colorpicker-component\">",
"<input type=\"text\" class=\"form-control\" id='\(fieldsetPath)' name=\"\(fieldsetPath)\" value=\"\(inputValue)\">",
"<span class=\"input-group-addon\"><i></i></span>",
"</div></div><script>",
"$(function() { $('#\(fieldsetPath)-cp').colorpicker(); });",
"</script>"
]
if let label = label {
template.insert("<label class=\"control-label\" for=\"\(fieldsetPath)\">\(label)</label>", at: 1)
}
return .bytes(template.joined(separator: "\n").bytes)
}
}
| mit | 8160b4df23e9bd5280135076d9d49c1b | 40.225 | 147 | 0.56883 | 4.305483 | false | false | false | false |
TMTBO/TTAImagePickerController | TTAImagePickerController/Classes/TTAImagePickerController.swift | 1 | 9906 | //
// TTAImagePickerController.swift
// Pods
//
// Created by TobyoTenma on 17/06/2017.
// Copyright (c) 2017 TMTBO. All rights reserved.
//
import Photos
public class TTAImagePickerController: UINavigationController, TTAImagePickerControllerCompatiable {
public weak var pickerDelegate: TTAImagePickerControllerDelegate?
public var allowDeleteImage = false {
didSet {
configPicker { (_, assetVc) in
assetVc?.allowDeleteImage = allowDeleteImage
}
}
}
public var allowTakePicture = true {
didSet {
configPicker { (_, assetVc) in
assetVc?.allowTakePicture = allowTakePicture
}
}
}
/// Show Lagre titles
/// Only Support for iOS 11
open var supportLargeTitles: Bool = false {
didSet {
configPicker { (albumVc, _) in
albumVc?.supportLargeTitles = supportLargeTitles
}
}
}
/// The max num image of the image picker can pick, default is 9
public var maxPickerNum = 9 {
didSet {
configPicker { (albumVc, assetVc) in
albumVc?.maxPickerNum = maxPickerNum
assetVc?.maxPickerNum = maxPickerNum
}
}
}
/// The selected asset
public var selectedAsset: [TTAAsset] = [] {
didSet {
updateSelectedAsset()
}
}
/// The tint color which item was selected, default is `UIColor(red: 0, green: 122.0 / 255.0, blue: 1, alpha: 1)`
public var selectItemTintColor: UIColor? = UIColor(red: 0, green: 122.0 / 255.0, blue: 1, alpha: 1) {
didSet {
configPicker { (albumVc, assetVc) in
albumVc?.selectItemTintColor = selectItemTintColor
assetVc?.selectItemTintColor = selectItemTintColor
}
}
}
/// NavigationBar tintColor
public var tintColor: UIColor = UIColor(red: 0, green: 122.0 / 255.0, blue: 1, alpha: 1) {
didSet {
navigationBar.tintColor = tintColor
navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: tintColor]
guard let splitController = splitController else { return }
_ = splitController.viewControllers.map { (viewController) in
guard let viewController = viewController as? UINavigationController else { return }
viewController.toolbar.tintColor = tintColor
viewController.navigationBar.tintColor = tintColor
viewController.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: tintColor]
}
}
}
/// NavigationBar barTintColor
public var barTintColor: UIColor? {
didSet {
navigationBar.barTintColor = barTintColor
guard let splitController = splitController else { return }
_ = splitController.viewControllers.map { (viewController) in
guard let viewController = viewController as? UINavigationController else { return }
viewController.navigationBar.barTintColor = barTintColor
viewController.toolbar.barTintColor = barTintColor
}
}
}
fileprivate(set) var splitController: UISplitViewController? = UISplitViewController()
public convenience init(selectedAsset: [TTAAsset]?) {
type(of: self).prepareIconFont()
let rootVc = UIViewController()
self.init(rootViewController: rootVc)
prepareNavigationItems()
self.selectedAsset = selectedAsset ?? []
updateSelectedAsset()
guard let splitController = splitController else { return }
addChild(splitController)
rootVc.view.addSubview(splitController.view)
splitController.view.backgroundColor = .clear
splitController.preferredDisplayMode = .allVisible
splitController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
deinit {
splitController = nil
#if DEBUG
print("TTAImagePickerController >>>>>> deinit")
#endif
}
}
// MARK: - UI
extension TTAImagePickerController {
func prepareNavigationItems() {
guard let topViewController = topViewController else { return }
topViewController.navigationItem.title = "\(TTAImagePickerController.self)"
topViewController.navigationItem.hidesBackButton = true
let cancelItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(didClickCancelItem))
topViewController.navigationItem.rightBarButtonItem = cancelItem
}
func updateSelectedAsset() {
configPicker { (_, assetVc) in
assetVc?.selected = selectedAsset.map { $0.original }
}
}
}
// MARK: - Life Cycle
extension TTAImagePickerController {
public override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
checkPermission()
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard let splitController = splitController else { return }
splitController.view.frame = view.bounds
}
}
// MARK: - Private
fileprivate extension TTAImagePickerController {
func configPicker(_ handler: (_ albumVc: TTAAlbumPickerViewController?, _ assetVc: TTAAssetPickerViewController?) -> ()) {
guard let splitController = splitController else { return }
_ = splitController.viewControllers.map { (vc) in
guard let nav = vc as? UINavigationController,
let rootVc = nav.topViewController else { return }
if let albumVc = rootVc as? TTAAlbumPickerViewController {
handler(albumVc, nil)
} else if let assetVc = rootVc as? TTAAssetPickerViewController {
handler(nil, assetVc)
}
}
}
}
// MARK: - Check Permission
extension TTAImagePickerController {
func checkPermission() {
func permissionDenied() {
setNavigationBarHidden(false, animated: false)
showPermissionView(with: .photo)
}
func startSetup() {
setNavigationBarHidden(true, animated: false)
prepareSplitController()
}
TTAImagePickerManager.checkPhotoLibraryPermission { (isAuthorized) in
isAuthorized ? startSetup() : permissionDenied()
}
}
}
// MARK: - Actions
extension TTAImagePickerController {
@objc func didClickCancelItem() {
dismiss(animated: true, completion: nil)
}
}
// MARK: - Generate Controllers
extension TTAImagePickerController {
func prepareSplitController() {
guard let splitController = splitController else { return }
TTACachingImageManager.prepareCachingManager()
let albums = TTAImagePickerManager.fetchAlbums()
if let album = albums.first {
let pickerController = _generateAssetController(with: album, selectedAsset: selectedAsset)
let collectionController = _generateCollectionController(with: albums, pickerController: pickerController)
splitController.viewControllers = [collectionController, pickerController]
}
}
func _generateCollectionController(with collections: [TTAAlbum], pickerController: UINavigationController) -> UINavigationController {
let assetCollectionController = TTAAlbumPickerViewController(albums: collections, pickerController: pickerController)
assetCollectionController.maxPickerNum = maxPickerNum
assetCollectionController.selectItemTintColor = selectItemTintColor
TTACachingImageManager.addObserver(assetCollectionController)
let nav = UINavigationController(rootViewController: assetCollectionController)
return nav
}
func _generateAssetController(with album: TTAAlbum, selectedAsset: [TTAAsset]) -> UINavigationController {
let assetPickerController = TTAAssetPickerViewController(album: album, selectedAsset: selectedAsset.map({ $0.original }))
assetPickerController.maxPickerNum = maxPickerNum
assetPickerController.selectItemTintColor = selectItemTintColor
assetPickerController.delegate = self
let nav = UINavigationController(rootViewController: assetPickerController)
return nav
}
}
// MARK: - Prepareation
extension TTAImagePickerController {
static func prepareIconFont() {
guard let url = Bundle.imagePickerBundle().url(forResource: "iconfont", withExtension: ".ttf") else { return }
UIFont.registerFont(with: url, fontName: "iconfont")
}
}
// MARK: - TTAAssetPickerViewControllerDelegate
extension TTAImagePickerController: TTAAssetPickerViewControllerDelegate {
func assetPickerController(_ picker: TTAAssetPickerViewController, didFinishPicking assets: [PHAsset]) {
fetchImages(with: assets) { [weak self] (images) in
guard let `self` = self else { return }
self.pickerDelegate?.imagePickerController(self, didFinishPicking: images, assets: assets.map({ TTAAsset(asset: $0) }))
self.dismiss(animated: true, completion: nil)
}
}
}
extension UISplitViewController {
open override var prefersStatusBarHidden: Bool {
guard let nav = viewControllers.last as? UINavigationController,
let visibleVc = nav.visibleViewController else { return false }
return visibleVc.prefersStatusBarHidden
}
open override var preferredStatusBarStyle: UIStatusBarStyle {
guard let nav = viewControllers.last as? UINavigationController,
let visibleVc = nav.visibleViewController else { return .default }
return visibleVc.preferredStatusBarStyle
}
}
| mit | af68f5f48ebc71f1016b18d8f25df2ab | 35.825279 | 138 | 0.661518 | 5.46086 | false | false | false | false |
Promptus/ExtensionsFramework | ExtensionsFramework/SwiftExtensions/date/Date-Formatter.swift | 1 | 2985 | //
// Date-Formatter.swift
// MSSNGR
//
// Created by Alexandra Ionasc on 11/10/16.
// Copyright © 2016 Promptus. All rights reserved.
//
import Foundation
public enum ISO8601Type: String {
case year = "yyyy"
case yearMonth = "yyyy-MM"
case date = "yyyy-MM-dd"
case hourMinute = "HH:mm"
case time = "HH:mm:ss"
case dateTime = "yyyy-MM-dd'T'HH:mmZZZZZ"
case full = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
case extended = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
}
public struct DateFormat {
public static let Default = "yyyy-MM-dd'T'HH:mm:ss"
public static let DateTimeShort = "ddMMYYHH:mm"
public static let TimeShort = "jj:mm"
public static let DayMonth = "EEEEdMMMM"
public static let LongDateTimeFormat = "EEEdMMMM jj:mm"
public static let Date = "EEEEdMMMMYYYY"
public static let DateShort = "EEEdMM"
}
public extension Date {
static func parseISO8601String(_ isoStringDate: Any?, isoType: ISO8601Type = .full) -> Date? {
guard let isoString = isoStringDate as? String else { return nil }
let formatter = CustomDateFormatter.formatter
formatter.dateFormat = isoType.rawValue
formatter.calendar = CustomDateFormatter.gregorianCalendar
return formatter.date(from: isoString)
}
func toISO8601String(isoType iso8601type: ISO8601Type = .full) -> String? {
return toString(format: iso8601type.rawValue)
}
func toString(format dateFormat: String, calendar: Calendar = Calendar.current) -> String? {
let dateFormatter = CustomDateFormatter.formatter
dateFormatter.dateFormat = dateFormat
dateFormatter.timeZone = NSTimeZone.default
dateFormatter.calendar = calendar
return dateFormatter.string(from: self)
}
func toString(template templateFormat: String, locale: Locale = Locale.current, calendar: Calendar = Calendar.current) -> String? {
let dateFormatter = CustomDateFormatter.createDateFormatterFromTemplate(templateFormat, locale: locale)
dateFormatter.timeZone = NSTimeZone.default
dateFormatter.locale = locale
dateFormatter.calendar = calendar
return dateFormatter.string(from: self)
}
}
public class CustomDateFormatter {
public static var gregorianCalendar: Calendar = {
return Calendar(identifier: .gregorian)
}()
public static var formatter: Foundation.DateFormatter = {
let formatter = Foundation.DateFormatter()
return formatter
}()
public static func createDateFormatterFromTemplate(_ dateTemplateFormat: String = DateFormat.Default, locale: Locale? = Locale.current) -> Foundation.DateFormatter {
let templateFromat = Foundation.DateFormatter.dateFormat(fromTemplate: dateTemplateFormat, options: 0, locale: locale)
formatter.dateFormat = templateFromat ?? dateTemplateFormat
return formatter
}
}
| mit | 5d773aa41d06647fa360a2b02b7db609 | 35.839506 | 169 | 0.682976 | 4.268956 | false | false | false | false |
bradhilton/HttpRequest | Pods/Convertible/Convertible/Swift Extensions/Optional+Convertible.swift | 1 | 1241 | //
// Optional+Convertible.swift
// Convertibles
//
// Created by Bradley Hilton on 6/13/15.
// Copyright © 2015 Skyvive. All rights reserved.
//
import Foundation
extension Optional : JsonConvertible {
public static func initializeWithJson(json: JsonValue, options: [ConvertibleOption]) throws -> Optional {
switch json {
case .Null(_): return nil
default:
if let type = Wrapped.self as? JsonInitializable.Type, let value = try type.initializeWithJson(json, options: options) as? Wrapped {
return self.init(value)
} else {
throw ConvertibleError.CannotCreateType(type: self, fromJson: json)
}
}
}
public func serializeToJsonWithOptions(options: [ConvertibleOption]) throws -> JsonValue {
let error = ConvertibleError.NotJsonSerializable(type: Wrapped.self)
guard Wrapped.self is JsonSerializable.Type else { throw error }
if let object = self {
guard let serializable = object as? JsonSerializable else { throw error }
return try serializable.serializeToJsonWithOptions(options)
} else {
return JsonValue.Null(NSNull())
}
}
}
| mit | 4829fa6e3a9f695d20fbd9e6d3373bfa | 33.444444 | 144 | 0.639516 | 4.769231 | false | false | false | false |
TouchInstinct/LeadKit | Sources/Classes/Views/DefaultPlaceholders/TextWithButtonPlaceholder.swift | 1 | 2222 | //
// Copyright (c) 2018 Touch Instinct
//
// 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 UIKit
internal final class TextWithButtonPlaceholder: UIView {
typealias TapHandler = () -> Void
private let tapHandler: TapHandler
init(title: TextPlaceholderView.PlaceholderText,
buttonTitle: TextPlaceholderView.PlaceholderText,
tapHandler: @escaping TapHandler) {
self.tapHandler = tapHandler
super.init(frame: .zero)
let textPlaceholder = TextPlaceholderView(title: title)
let button = UIButton(type: .custom)
button.backgroundColor = .lightGray
button.setTitle(buttonTitle.rawValue, for: .normal)
button.addTarget(self, action: #selector(buttonDidTapped(_:)), for: .touchUpInside)
let stackView = UIStackView(arrangedSubviews: [textPlaceholder, button])
stackView.axis = .vertical
addSubview(stackView)
stackView.setToCenter(withSize: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func buttonDidTapped(_ button: UIButton) {
tapHandler()
}
}
| apache-2.0 | cde6759b19f6564194af2e1ad7e4d07f | 35.42623 | 91 | 0.716022 | 4.677895 | false | false | false | false |
threefoldphotos/VWWAnnotationFanoutView | VWWAnnotationFanoutViewExampleSwift/ViewController.swift | 1 | 2723 | //
// ViewController.swift
// VWWAnnotationFanoutViewExampleSwift
//
// Created by Zakk Hoyt on 6/16/15.
// Copyright (c) 2015 Zakk Hoyt. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let annotations: [HotelAnnotation] = HotelAnnotation.readHotelsDataFile()
let annotation = annotations.first
println("Lat:\(annotation?.coordinate.latitude) Long:\(annotation?.coordinate.longitude)")
mapView.delegate = self
mapView.addAnnotations(annotations)
let span = MKCoordinateSpanMake(0.5, 0.5)
let center = CLLocationCoordinate2DMake(37.75, -122.45)
let region = MKCoordinateRegionMake(center, span)
mapView.setRegion(region, animated: true)
}
func annotationViewSelected(annotationView: MKAnnotationView) {
println("User tapped annotation view")
}
}
extension ViewController : MKMapViewDelegate {
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
let CUSTOM_PINS = true
if CUSTOM_PINS {
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(HotelAnnotationView.HotelAnnotationViewIdentifier)
if let hotelAnnotationView = annotationView {
return hotelAnnotationView
} else {
annotationView = HotelAnnotationView(annotation: annotation, reuseIdentifier: HotelAnnotationView.HotelAnnotationViewIdentifier)
return annotationView
}
} else {
let pin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")
pin.pinColor = MKPinAnnotationColor.Green
pin.animatesDrop = true
return pin
}
}
func mapView(mapView: MKMapView!, didSelectAnnotationView view: MKAnnotationView!) {
let annotationViews: Set = VWWAnnotationFanoutView.annotationViewsOverlappingAnnotationView(view, mapView: mapView)
if annotationViews.count == 1 {
annotationViewSelected(view)
} else {
let point = view.center
let fanout = VWWAnnotationFanoutView()
let annotationViewsArray = Array(annotationViews)
fanout.showContextForMapView(mapView, atPoint: point, menuViews: annotationViewsArray, completionBlock: { (index) -> Void in
// let view = annotationViewsArray[index]
self.annotationViewSelected(view)
})
}
}
}
| apache-2.0 | 973034c364b941da8694dc61c85636a7 | 36.30137 | 144 | 0.658465 | 5.467871 | false | false | false | false |
hhcszgd/cszgdCode | weibo1/weibo1/classes/Model/Status.swift | 1 | 2683 | //
// Status.swift
// weibo1
//
// Created by WY on 15/11/30.
// Copyright © 2015年 WY. All rights reserved.
//
import UIKit
class Status: NSObject {
//转发的微博
var retweeted_status : Status?//这个属性的类型跟Status模型的层次结构是一模一样的
///微博创建时间
var created_at: String?
//微博ID
var id: Int = 0
//微博正文
var text: String?
//微博来源
var source: String?
//添加user属性
var user: User?
//配图数组属性
var pic_urls: [[String : String]]?{
didSet {
guard let urls = pic_urls else {
print("数据加载失败")
return
}
// print("在微博moxing中打印图片链接数组的个数\(pic_urls!.count)")////////////打印有值
imageURLs = [NSURL]()//实例化属性
for oneURLDic in urls {
let oneURLStr = oneURLDic["thumbnail_pic"]
let url = NSURL(string: oneURLStr!)!
// print("在微博moxing中打印图片链接数组的个数\(url)")//在这儿也有值
imageURLs?.append(url)//这一步计算有问题
// print("在微博moxing中打印图片链接数组的个数\(imageURLs?.count)")
}
// print("在微博moxing中打印图片链接数组的个数\(imageURLs?.count)")////////////打印全空
}
}
var imageURLs: [NSURL]?
//定义同一的图片数组 原创微博 + 转发微博
var pictureURLs: [NSURL]? {
if retweeted_status != nil {
return retweeted_status?.imageURLs
}
return imageURLs
}
init (dic : [String : AnyObject ]){
super.init()
setValuesForKeysWithDictionary(dic)
}
override func setValue(value: AnyObject?, forKey key: String) {
if key == "user" {//当键为user时 , 这个键值的转换就不让它走系统的方法, 自己设置转换方法
if let tem = value as? [String : AnyObject] { //MARK: 为什么一定要用 ? 不能用!
user = User(dic: tem)
}
return
}
//判断user键 对应的value 能否转化为 User(dict 对应的字典
if key == "retweeted_status" {
if let dict = value as? [String : AnyObject] {
//字典转模型
retweeted_status = Status(dic: dict)
}
return
}
super.setValue(value, forKey: key)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
| apache-2.0 | 385a65452c5a1253ccd068af858c54af | 26.268293 | 79 | 0.513864 | 3.841924 | false | false | false | false |
elegion/ios-Tretryakovka | Source/GalleryViewController.swift | 1 | 6336 | //
// GalleryViewController.swift
// Tretyakovka
//
// Created by Sergey Rakov on 08.09.16.
// Copyright © 2016 e-Legion. All rights reserved.
//
import UIKit
class GalleryViewController: UIViewController {
private var navigationBar: UINavigationBar!
private var galleryView: GalleryView!
private var navBarHideRecognizer: UITapGestureRecognizer!
//MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI() {
automaticallyAdjustsScrollViewInsets = false
view.backgroundColor = UIColor.whiteColor()
navigationBar = UINavigationBar(frame: CGRectMake(0, 0, view.bounds.width, 64))
navigationBar.autoresizingMask = [.FlexibleWidth, .FlexibleBottomMargin]
navigationBar.delegate = self
view.addSubview(navigationBar)
galleryView = GalleryView(frame: view.bounds)
galleryView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
galleryView.toggleZoomOnDoubleTap = true
if images.count > 0 {
galleryView.images = images
}
view.insertSubview(galleryView, belowSubview: navigationBar)
navBarHideRecognizer = UITapGestureRecognizer(target: self, action: #selector(onViewTapped))
navBarHideRecognizer.delegate = self
view.addGestureRecognizer(navBarHideRecognizer)
}
deinit {
galleryIndexObservationEnabled = false
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
setNavigationBarCustomized(true)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
galleryIndexObservationEnabled = true
onGalleryIndexChanged(nil)
resetNavigationBar()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
galleryIndexObservationEnabled = false
setNavigationBarCustomized(false)
}
//MARK: - Public
var images: [GalleryImage] = [GalleryImage]() {
didSet {
galleryView?.images = images
}
}
var backItem: UIBarButtonItem?
var backButtonAction: ((Void) -> (Void))?
//MARK: - UI Events
func onViewTapped() {
self.navigationBarHidden = !navigationBarHidden
}
private func onBackPressed() {
if let backButtonAction = backButtonAction {
backButtonAction()
} else {
if navigationController != nil {
navigationController?.popViewControllerAnimated(true)
} else {
dismissViewControllerAnimated(true, completion: nil)
}
}
}
//MARK: - Observation
private var galleryIndexObservationEnabled: Bool = false {
didSet {
guard galleryIndexObservationEnabled != oldValue else { return }
if galleryIndexObservationEnabled {
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(onGalleryIndexChanged),
name: GalleryViewIndexDidChangeNotification,
object: galleryView)
} else {
NSNotificationCenter.defaultCenter().removeObserver(self,
name: GalleryViewIndexDidChangeNotification,
object: galleryView)
}
}
}
func onGalleryIndexChanged(notification: NSNotification?) {
guard let toggleZoomRecognizer = galleryView.activeToggleZoomGestureRecognizer else { return }
navBarHideRecognizer.requireGestureRecognizerToFail(toggleZoomRecognizer)
}
//MARK: - Private
private var navigationBarHidden: Bool {
get {
return navigationBar.alpha < 1
}
set {
UIView.animateWithDuration(0.25) {
self.navigationBar.alpha = newValue ? 0 : 1
self.view.backgroundColor = newValue ? UIColor.blackColor() : UIColor.whiteColor()
}
}
}
private var originalNavigationBarHidden: Bool = false
func setNavigationBarCustomized(customized: Bool) {
let backNavigationItem = UINavigationItem()
var backItem = self.backItem
if backItem == nil {
backItem = UIBarButtonItem(barButtonSystemItem: .Done, target: nil, action: nil)
}
backNavigationItem.backBarButtonItem = backItem
navigationBar.setItems([backNavigationItem, navigationItem], animated: false)
guard let navigationController = navigationController else { return }
if customized {
originalNavigationBarHidden = navigationController.navigationBarHidden
navigationController.setNavigationBarHidden(true, animated: true)
} else {
navigationController.setNavigationBarHidden(originalNavigationBarHidden, animated: true)
}
}
/// Fix disappearing title after viewDidAppear
private func resetNavigationBar() {
let delegate = navigationBar.delegate
navigationBar.delegate = nil // disable pop processing
navigationBar.popNavigationItemAnimated(false)
navigationBar.pushNavigationItem(navigationItem, animated: false)
navigationBar.delegate = delegate
}
}
extension GalleryViewController: UINavigationBarDelegate {
func navigationBar(navigationBar: UINavigationBar, shouldPopItem item: UINavigationItem) -> Bool {
navigationBar.items = [navigationItem] // weird crash on pop on iOS 8 otherwise
onBackPressed()
return false // incorrect nav bar state on deallocation otherwise
}
}
extension GalleryViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
guard let touchView = touch.view else { return true }
return !touchView.isDescendantOfView(navigationBar)
}
}
| mit | 93950e4d4f30893290bf97cfbc9eb225 | 33.429348 | 112 | 0.628729 | 6.097209 | false | false | false | false |
arbitur/Func | FuncExample/FuncExample/AppDelegate.swift | 1 | 3466 | //
// AppDelegate.swift
// FuncExample
//
// Created by Philip Fryklund on 28/Feb/17.
// Copyright © 2017 Arbitur. All rights reserved.
//
import UIKit
import Func
import Alamofire
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder {
var window: UIWindow?
fileprivate func loadWindow() {
let window = UIWindow(frame: UIScreen.main.bounds)
window.makeKeyAndVisible()
self.window = window
// let vc = Page1()
// let nc = UINavigationController(rootViewController: vc)
// nc.navigationBar.isTranslucent = false
// window.rootViewController = nc
// let slide = SlideMenuController()
// slide.rootViewController = RootVC()
// slide.menuViewController = MenuVC()
// window.rootViewController = slide
let slide2 = SlideMenuController()
slide2.rootViewController = RootVC()
slide2.menuViewController = MenuVC()
window.rootViewController = slide2
// let tabController = SlideTabController_NEW()
// tabController.addChildViewController(RootVC())
// tabController.addChildViewController(RootVC())
// tabController.addChildViewController(RootVC())
// window.rootViewController = tabController
print("iPhone screen size:", UIScreen.main.screenSize.rawValue)
}
}
class MenuVC: DebugViewController {
weak var controller: SlideMenuController?
func attached(to controller: SlideMenuController) {
}
private class VC: DebugViewController {
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.slideMenuController?.openMenu()
}
override func loadView() {
let label = UILabel(font: UIFont.systemFont(ofSize: 18), alignment: .center)
label.backgroundColor = .white
label.text = self.title
label.isUserInteractionEnabled = true
self.view = label
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let vc = VC()
vc.title = "Text \(Random.range(0..<10))"
controller?.rootViewController = vc
self.dismiss(animated: true, completion: nil)
}
override func loadView() {
self.view = UIView(backgroundColor: .red)
}
}
class RootVC: DebugViewController {
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let vc = RootVC()
vc.title = "Text \(Random.range(0..<10))"
self.slideMenuController?.rootViewController = vc
}
override func loadView() {
let label = UILabel()
label.backgroundColor = .random
label.isUserInteractionEnabled = true
label.textAlignment = .center
label.textColor = .white
label.text = self.title ?? "RootVC"
self.view = label
}
}
extension AppDelegate: UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// loadWindow()
// let color = UIColor.cyan
// print(color.rgba)
// print(color.hsl)
// print(color.hsb)
//
// print()
//
// do {
// try Archiver.archive(["a": 1, "b": "cdefg"], forKey: "test")
// }
// catch {
// print(error.localizedDescription)
// }
//
// let test: Dict? = Archiver.unarchive(forKey: "test")
// print("Unarchived", test ?? "nil")
// GeocodingAPI.loggingMode = .url
// GeocodingAPI.key = "AIzaSyCBWku312Br8Rsh8YXhzNkDN3vsy2Iz6yA"
// GeocodingAPI.request(Geocode(address: "Östermalmstorg 1, Stockholm"))
// .success { status, response in
// print(response)
// }
// .failure { error in
// print(error)
// }
return true
}
}
| mit | c7d27d0bb737bbfa2f48e54898145479 | 20.65 | 141 | 0.700635 | 3.541922 | false | false | false | false |
xxxAIRINxxx/ViewPagerController | Sources/UIView+AutoLayout.swift | 1 | 4009 | //
// UIView+AutoLayout.swift
// ViewPagerController
//
// Created by xxxAIRINxxx on 2016/01/05.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
public extension UIView {
public func checkTranslatesAutoresizing(_ withView: UIView?, toView: UIView?) {
if self.translatesAutoresizingMaskIntoConstraints == true {
self.translatesAutoresizingMaskIntoConstraints = false
}
if let _withView = withView {
if _withView.translatesAutoresizingMaskIntoConstraints == true {
_withView.translatesAutoresizingMaskIntoConstraints = false
}
}
if let _toView = toView {
if _toView.translatesAutoresizingMaskIntoConstraints == true {
_toView.translatesAutoresizingMaskIntoConstraints = false
}
}
}
public func addPin(_ withView:UIView, attribute:NSLayoutAttribute, toView:UIView?, constant:CGFloat) -> NSLayoutConstraint {
checkTranslatesAutoresizing(withView, toView: toView)
return addPinConstraint(self, withItem: withView, toItem: toView, attribute: attribute, constant: constant)
}
public func addPin(_ withView:UIView, isWithViewTop:Bool, toView:UIView?, isToViewTop:Bool, constant:CGFloat) -> NSLayoutConstraint {
checkTranslatesAutoresizing(withView, toView: toView)
return addConstraint(
self,
relation: .equal,
withItem: withView,
withAttribute: (isWithViewTop == true ? .top : .bottom),
toItem: toView,
toAttribute: (isToViewTop == true ? .top : .bottom),
constant: constant
)
}
public func allPin(_ subView: UIView) {
checkTranslatesAutoresizing(subView, toView: nil)
_ = addPinConstraint(self, withItem: subView, toItem: self, attribute: .top, constant: 0.0)
_ = addPinConstraint(self, withItem: subView, toItem: self, attribute: .bottom, constant: 0.0)
_ = addPinConstraint(self, withItem: subView, toItem: self, attribute: .left, constant: 0.0)
_ = addPinConstraint(self, withItem: subView, toItem: self, attribute: .right, constant: 0.0)
}
// MARK: NSLayoutConstraint
public func addPinConstraint(_ parentView: UIView, withItem:UIView, toItem:UIView?, attribute:NSLayoutAttribute, constant:CGFloat) -> NSLayoutConstraint {
return addConstraint(
parentView,
relation: .equal,
withItem: withItem,
withAttribute: attribute,
toItem: toItem,
toAttribute: attribute,
constant: constant
)
}
public func addWidthConstraint(_ view: UIView, constant:CGFloat) -> NSLayoutConstraint {
return addConstraint(
view,
relation: .equal,
withItem: view,
withAttribute: .width,
toItem: nil,
toAttribute: .width,
constant: constant
)
}
public func addHeightConstraint(_ view: UIView, constant:CGFloat) -> NSLayoutConstraint {
return addConstraint(
view,
relation: .equal,
withItem: view,
withAttribute: .height,
toItem: nil,
toAttribute: .height,
constant: constant
)
}
public func addConstraint(_ addView: UIView, relation: NSLayoutRelation, withItem:UIView, withAttribute:NSLayoutAttribute, toItem:UIView?, toAttribute:NSLayoutAttribute, constant:CGFloat) -> NSLayoutConstraint {
let constraint = NSLayoutConstraint(
item: withItem,
attribute: withAttribute,
relatedBy: relation,
toItem: toItem,
attribute: toAttribute,
multiplier: 1.0,
constant: constant
)
addView.addConstraint(constraint)
return constraint
}
}
| mit | 521705acfc01f618739cceb2e62ddbb0 | 35.108108 | 215 | 0.615269 | 5.329787 | false | false | false | false |
tomoponzoo/TagsView | Classes/TagsView.swift | 1 | 7517 | //
// TagsView.swift
// TagsView
//
// Created by Tomoki Koga on 2017/03/08.
// Copyright © 2017年 tomoponzoo. All rights reserved.
//
import UIKit
let unassignedTag = -1
open class TagsView: UIView {
public weak var dataSource: TagsViewDataSource?
public weak var delegate: TagsViewDelegate?
public var preferredMaxLayoutWidth: CGFloat = UIScreen.main.bounds.width
public var allowsMultipleSelection = false
public var numberOfTags: Int {
return layoutProperties.numberOfTags
}
public var numberOfRows: Rows {
return layoutProperties.numberOfRows
}
public var alignment: Alignment {
return layoutProperties.alignment
}
public var padding: UIEdgeInsets {
return layoutProperties.padding
}
public var spacer: Spacer {
return layoutProperties.spacer
}
var layoutProperties = LayoutProperties()
var layout: Layout?
var tagViewNibs = [String: UINib]()
var supplementaryTagViewNib: UINib?
var tagViews: [TagView] {
return subviews.flatMap { $0 as? TagView }
}
var supplementaryTagView: SupplementaryTagView? {
return subviews.flatMap { $0 as? SupplementaryTagView }.first
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
public func registerTagView(nib: UINib?, forReuseIdentifier reuseIdentifier: String = "default") {
guard let nib = nib else { return }
tagViewNibs[reuseIdentifier] = nib
}
public func registerSupplementaryTagView(nib: UINib?) {
supplementaryTagViewNib = nib
}
public func reloadData() {
layoutProperties = resetLayoutProperties()
tagViews.forEach { (tagView) in
tagView.tag = unassignedTag
}
(0..<numberOfTags).forEach { (index) in
_ = self.dataSource?.tagsView(self, viewForIndexAt: index)
}
_ = dataSource?.supplementaryTagView(in: self)
layout = LayoutEngine(tagsView: self, preferredMaxLayoutWidth: preferredMaxLayoutWidth).layout()
invalidateIntrinsicContentSize()
}
public func selectTag(at index: Int) {
if let tagView = tagView(at: index) {
selectTag(tagView: tagView)
}
}
public func deselectTag(at index: Int) {
tagView(at: index)?.isSelected = false
}
public func index(for view: TagView) -> Int? {
return subviews.index(of: view)
}
public func tagView(at index: Int) -> TagView? {
return index < tagViews.count ? tagViews[index] : nil
}
public var indexForSupplementaryView: Int? {
guard let layout = layout, let supplementaryColumn = layout.supplementaryColumn else {
return nil
}
var index = 0
for column in layout.columns {
if column.minY < supplementaryColumn.minY {
index += 1
} else if column.minX < supplementaryColumn.minX {
index += 1
} else {
break
}
}
return index
}
}
// MARK: - Private
extension TagsView {
func setupView() {
}
func newTagView(for index: Int, withReuseIdentifier reuseIdentifier: String) -> TagView {
let tagView = tagViewNibs[reuseIdentifier]?.instantiate(withOwner: nil, options: nil).first as? TagView ?? TagView()
tagView.translatesAutoresizingMaskIntoConstraints = false
tagView.reuseIdentifier = reuseIdentifier
tagView.tag = index
insertSubview(tagView, at: index)
return tagView
}
func newSupplementaryTagView() -> SupplementaryTagView? {
guard let supplementaryTagView = supplementaryTagViewNib?.instantiate(withOwner: nil, options: nil).first as? SupplementaryTagView else { return nil }
supplementaryTagView.translatesAutoresizingMaskIntoConstraints = false
addSubview(supplementaryTagView)
return supplementaryTagView
}
func selectTag(tagView: TagView, isEvent: Bool = false) {
if allowsMultipleSelection {
if isEvent {
tagView.isSelected = !tagView.isSelected
} else {
tagView.isSelected = true
}
} else {
if !tagView.isSelected {
if let selectedTagView = tagViews.filter({ $0.isSelected }).first {
selectedTagView.isSelected = false
}
}
tagView.isSelected = true
}
}
func tagView(at index: Int, withReuseIdentifier reuseIdentifier: String) -> TagView? {
if let tagView = tagViews.first(where: { $0.tag == index }), tagView.reuseIdentifier == reuseIdentifier {
return tagView
}
if let tagView = tagViews.first(where: { $0.reuseIdentifier == reuseIdentifier && $0.tag == unassignedTag }) {
tagView.tag = index
return tagView
}
return nil
}
}
// MARK: - Event handle
extension TagsView {
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let view = touches.first?.view as? BaseTagView {
view.isHighlighted = true
}
}
open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first, let view = touch.view as? BaseTagView {
let point = touch.location(in: view)
view.isHighlighted = view.bounds.contains(point)
}
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first, let view = touch.view as? BaseTagView {
let point = touch.location(in: view)
view.isHighlighted = false
if view.bounds.contains(point) {
if let tagView = view as? TagView, let index = index(for: tagView) {
selectTag(tagView: tagView, isEvent: true)
delegate?.tagsView(self, didSelectItemAt: index)
}
if let _ = view as? SupplementaryTagView {
view.isSelected = !view.isSelected
delegate?.didSelectSupplementaryItem(self)
}
}
}
}
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
if let view = touches.first?.view as? BaseTagView {
view.isHighlighted = false
}
}
}
// MARK: - Recycle views
extension TagsView {
open func dequeueReusableTagView(for index: Int, withReuseIdentifier reuseIdentifier: String = "default") -> TagView {
if let tagView = tagView(at: index, withReuseIdentifier: reuseIdentifier) {
insertSubview(tagView, at: index)
return tagView
}
return newTagView(for: index, withReuseIdentifier: reuseIdentifier)
}
open func dequeueReusableSupplementaryTagView() -> SupplementaryTagView? {
if let supplementaryTagView = supplementaryTagView {
return supplementaryTagView
}
return newSupplementaryTagView()
}
}
| mit | 7c18e7a9ed4798823920cd8f5885ea67 | 29.921811 | 158 | 0.60008 | 5.136022 | false | false | false | false |
troystribling/BlueCap | Examples/BlueCap/BlueCap/Peripheral/PeripheralManagerServiceCharacteristicViewController.swift | 1 | 5486 | //
// PeripheralManagerServiceCharacteristicViewController.swift
// BlueCap
//
// Created by Troy Stribling on 8/19/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
import CoreBluetooth
import BlueCapKit
class PeripheralManagerServiceCharacteristicViewController: UITableViewController {
var characteristic: MutableCharacteristic?
var peripheralManagerViewController: PeripheralManagerViewController?
@IBOutlet var uuidLabel: UILabel!
@IBOutlet var permissionReadableLabel: UILabel!
@IBOutlet var permissionWriteableLabel: UILabel!
@IBOutlet var permissionReadEncryptionLabel: UILabel!
@IBOutlet var permissionWriteEncryptionLabel: UILabel!
@IBOutlet var propertyBroadcastLabel: UILabel!
@IBOutlet var propertyReadLabel: UILabel!
@IBOutlet var propertyWriteWithoutResponseLabel: UILabel!
@IBOutlet var propertyWriteLabel: UILabel!
@IBOutlet var propertyNotifyLabel: UILabel!
@IBOutlet var propertyIndicateLabel: UILabel!
@IBOutlet var propertyAuthenticatedSignedWritesLabel: UILabel!
@IBOutlet var propertyExtendedPropertiesLabel: UILabel!
@IBOutlet var propertyNotifyEncryptionRequiredLabel: UILabel!
@IBOutlet var propertyIndicateEncryptionRequiredLabel: UILabel!
struct MainStoryboard {
static let peripheralManagerServiceCharacteristicValuesSegue = "PeripheralManagerServiceCharacteristicValues"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
if let characteristic = self.characteristic {
self.uuidLabel.text = characteristic.uuid.uuidString
self.permissionReadableLabel.text = self.booleanStringValue(characteristic.permissionEnabled(CBAttributePermissions.readable))
self.permissionWriteableLabel.text = self.booleanStringValue(characteristic.permissionEnabled(CBAttributePermissions.writeable))
self.permissionReadEncryptionLabel.text = self.booleanStringValue(characteristic.permissionEnabled(CBAttributePermissions.readEncryptionRequired))
self.permissionWriteEncryptionLabel.text = self.booleanStringValue(characteristic.permissionEnabled(CBAttributePermissions.writeEncryptionRequired))
self.propertyBroadcastLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.broadcast))
self.propertyReadLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.read))
self.propertyWriteWithoutResponseLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.writeWithoutResponse))
self.propertyWriteLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.write))
self.propertyNotifyLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.notify))
self.propertyIndicateLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.indicate))
self.propertyAuthenticatedSignedWritesLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.authenticatedSignedWrites))
self.propertyExtendedPropertiesLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.extendedProperties))
self.propertyNotifyEncryptionRequiredLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.notifyEncryptionRequired))
self.propertyIndicateEncryptionRequiredLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.indicateEncryptionRequired))
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let characteristic = self.characteristic {
self.navigationItem.title = characteristic.name
}
NotificationCenter.default.addObserver(self, selector:#selector(PeripheralManagerServiceCharacteristicViewController.didEnterBackground), name: UIApplication.didEnterBackgroundNotification, object:nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationItem.title = ""
NotificationCenter.default.removeObserver(self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
if segue.identifier == MainStoryboard.peripheralManagerServiceCharacteristicValuesSegue {
let viewController = segue.destination as! PeripheralManagerServicesCharacteristicValuesViewController
viewController.characteristic = self.characteristic
if let peripheralManagerViewController = self.peripheralManagerViewController {
viewController.peripheralManagerViewController = peripheralManagerViewController
}
}
}
@objc func didEnterBackground() {
Logger.debug()
if let peripheralManagerViewController = self.peripheralManagerViewController {
_ = self.navigationController?.popToViewController(peripheralManagerViewController, animated:false)
}
}
func booleanStringValue(_ value:Bool) -> String {
return value ? "YES" : "NO"
}
}
| mit | 4f286273f1650a1e8b327ce90c8158d4 | 52.262136 | 209 | 0.769231 | 5.982552 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Room/Views/Avatar/RoomAvatarView.swift | 1 | 2630 | //
// Copyright 2020 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import Reusable
final class RoomAvatarView: AvatarView, NibOwnerLoadable {
// MARK: - Properties
// MARK: Outlets
@IBOutlet private weak var cameraBadgeContainerView: UIView!
// MARK: Public
var showCameraBadgeOnFallbackImage: Bool = false
// MARK: - Setup
private func commonInit() {
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.loadNibContent()
self.commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.loadNibContent()
self.commonInit()
}
// MARK: - Lifecycle
override func layoutSubviews() {
super.layoutSubviews()
self.avatarImageView.layer.cornerRadius = self.avatarImageView.bounds.height/2
}
// MARK: - Public
override func fill(with viewData: AvatarViewDataProtocol) {
self.updateAvatarImageView(with: viewData)
// Fix layoutSubviews not triggered issue
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.setNeedsLayout()
}
}
// MARK: - Overrides
override func updateAccessibilityTraits() {
if self.isUserInteractionEnabled {
self.vc_setupAccessibilityTraitsButton(withTitle: VectorL10n.roomAvatarViewAccessibilityLabel, hint: VectorL10n.roomAvatarViewAccessibilityHint, isEnabled: true)
} else {
self.vc_setupAccessibilityTraitsImage(withTitle: VectorL10n.roomAvatarViewAccessibilityLabel)
}
}
override func updateAvatarImageView(with viewData: AvatarViewDataProtocol) {
super.updateAvatarImageView(with: viewData)
let hideCameraBadge: Bool
if self.showCameraBadgeOnFallbackImage {
hideCameraBadge = viewData.avatarUrl != nil
} else {
hideCameraBadge = true
}
self.cameraBadgeContainerView.isHidden = hideCameraBadge
}
}
| apache-2.0 | 2fef625128d24f983bce1848cd72fe36 | 27.901099 | 173 | 0.660456 | 4.87037 | false | false | false | false |
missiondata/transit | transit/transit/BusPrediction.swift | 1 | 1169 | //
// BusPrediction.swift
// Transit
//
// Created by Dan Hilton on 2/3/16.
// Copyright © 2016 MissionData. All rights reserved.
//
import Foundation
open class BusPrediction {
open var directionNum: Int?
open var directionText: String?
open var minutes: [Int]?
open var routeId: String?
open var tripId: String?
open var vehicleId: String?
init(json: JSON) {
self.directionNum = Int(json["DirectionNum"].string!)
self.directionText = json["DirectionText"].string
self.addMinutes(json["Minutes"].integer!)
self.routeId = json["RouteID"].string
self.tripId = json["TripID"].string
self.vehicleId = json["VehicleID"].string
}
init(directionText:String?, routeId:String?) {
self.directionText = directionText
self.routeId = routeId
}
open func addMinutes(_ min: Int) {
if self.minutes == nil {
self.minutes = [Int]()
}
self.minutes!.append(min)
}
open func minutesToString() -> String {
return minutes != nil ? minutes!.map { String($0) + "m" }.joined(separator: ", ") : ""
}
}
| mit | c4ca1204c18652b4aa64e704b2e72698 | 24.955556 | 94 | 0.600171 | 3.972789 | false | false | false | false |
XWJACK/Music | Music/Modules/Player/MusicLyricTableViewCell.swift | 1 | 1426 | //
// MusicLyricTableViewCell.swift
// Music
//
// Created by Jack on 5/24/17.
// Copyright © 2017 Jack. All rights reserved.
//
import UIKit
class MusicLyricTableViewCell: MusicTableViewCell {
private let lyricLabel: UILabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
isHiddenSeparator = true
normal(lyric: "")
lyricLabel.numberOfLines = 0
lyricLabel.textAlignment = .center
contentView.addSubview(lyricLabel)
lyricLabel.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(5)
make.bottom.equalToSuperview().offset(-5)
make.left.equalToSuperview().offset(5)
make.right.equalToSuperview().offset(-5)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func normal(lyric: String? = nil) {
if let lyric = lyric { lyricLabel.text = lyric }
lyricLabel.font = .font12
lyricLabel.textColor = .lightGray
}
func heightLight(lyric: String? = nil) {
if let lyric = lyric { lyricLabel.text = lyric }
lyricLabel.font = .font14
lyricLabel.textColor = .white
}
}
| mit | d277239f2ac8cbe70e97ea62fc74c18f | 26.941176 | 74 | 0.606316 | 4.672131 | false | false | false | false |
crazypoo/PTools | Pods/InAppViewDebugger/InAppViewDebugger/Snapshot.swift | 1 | 1642 | //
// Snapshot.swift
// InAppViewDebugger
//
// Created by Indragie Karunaratne on 3/31/19.
// Copyright © 2019 Indragie Karunaratne. All rights reserved.
//
import Foundation
import CoreGraphics
/// A snapshot of the UI element tree in its current state.
@objc(IAVDSnapshot) public final class Snapshot: NSObject {
/// Unique identifier for the snapshot.
@objc public let identifier = UUID().uuidString
/// Identifying information for the element, like its name and classification.
@objc public let label: ElementLabel
/// The frame of the element in its parent's coordinate space.
@objc public let frame: CGRect
/// Whether the element is hidden from view or not.
@objc public let isHidden: Bool
/// A snapshot image of the element in its current state.
@objc public let snapshotImage: CGImage?
/// The child snapshots of the snapshot (one per child element).
@objc public let children: [Snapshot]
/// The element used to create the snapshot.
@objc public let element: Element
/// Constructs a new `Snapshot`
///
/// - Parameter element: The element to construct the snapshot from. The
/// data stored in the snapshot will be the data provided by the element
/// at the time that this constructor is called.
@objc public init(element: Element) {
self.label = element.label
self.frame = element.frame
self.isHidden = element.isHidden
self.snapshotImage = element.snapshotImage
self.children = element.children.map { Snapshot(element: $0) }
self.element = element
}
}
| mit | 255dfbdc962a9d0f7d0b18d0207999ad | 33.1875 | 82 | 0.678854 | 4.609551 | false | false | false | false |
augmify/BluetoothKit | Source/BKDiscovery.swift | 13 | 2395 | //
// BluetoothKit
//
// Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth
//
// 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 CoreBluetooth
public func ==(lhs: BKDiscovery, rhs: BKDiscovery) -> Bool {
return lhs.remotePeripheral == rhs.remotePeripheral
}
/**
A discovery made while scanning, containing a peripheral, the advertisement data and RSSI.
*/
public struct BKDiscovery: Equatable {
// MARK: Properties
/// The advertised name derived from the advertisement data.
public var localName: String? {
return advertisementData[CBAdvertisementDataLocalNameKey] as? String
}
/// The data advertised while the discovery was made.
public let advertisementData: [String: AnyObject]
/// The remote peripheral that was discovered.
public let remotePeripheral: BKRemotePeripheral
/// The [RSSI (Received signal strength indication)](https://en.wikipedia.org/wiki/Received_signal_strength_indication) value when the discovery was made.
public let RSSI: Int
// MARK: Initialization
public init(advertisementData: [String: AnyObject], remotePeripheral: BKRemotePeripheral, RSSI: Int) {
self.advertisementData = advertisementData
self.remotePeripheral = remotePeripheral
self.RSSI = RSSI
}
}
| mit | 0763ec182d2d935443082bcbdaa51901 | 38.916667 | 158 | 0.728184 | 4.733202 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/01429-swift-typebase-getcanonicaltype.swift | 11 | 654 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
class B {
protocol a {
protocol P {
return d, A = b: C {
struct c, f.b = "A, length: c<T>(g<d {
protocol b {
}
extension A {
}
}
protocol A {
}
}
var b = A.init(h: B<T> d.d>()
}
protocol A {
case c) -> <T: B, Any, B<T>]].Iterator.c == e: d {
}
typealias e: e> a
| apache-2.0 | a6fb3899ff86aa2175cb7d432975d80c | 23.222222 | 78 | 0.665138 | 2.959276 | false | false | false | false |
Mohammad103/MSUtility | MSUtility/Classes/UITextField+Extenstion.swift | 1 | 648 | //
// UITextField+Extenstion.swift
// Le Cadeau
//
// Created by Mohammad Shaker on 1/21/16.
// Copyright © 2016 AMIT-Software. All rights reserved.
//
import UIKit
extension UITextField {
public func showExclamationMark() {
self.rightViewMode = .always
let exclamationIV = UIImageView(frame: CGRect(x: 0, y: 0, width: 16, height: 16))
exclamationIV.image = UIImage(named: "exclamation")
exclamationIV.contentMode = .scaleAspectFit
self.rightView = exclamationIV
}
public func hideExclamationMark() {
self.rightViewMode = .never
self.rightView = nil
}
}
| mit | 57dbb8c00f8a15587568190745859915 | 23.884615 | 89 | 0.646059 | 3.945122 | false | false | false | false |
OpenKitten/MongoKitten | Sources/MongoClient/Authenticate.swift | 2 | 3569 | import _MongoKittenCrypto
import Foundation
import MongoCore
import NIO
extension MongoConnection {
func authenticate(to source: String, with credentials: ConnectionSettings.Authentication) -> EventLoopFuture<Void> {
let namespace = MongoNamespace(to: "$cmd", inDatabase: source)
var credentials = credentials
if case .auto(let user, let pass) = credentials {
do {
credentials = try selectAuthenticationAlgorithm(forUser: user, password: pass)
} catch {
return eventLoop.makeFailedFuture(error)
}
}
switch credentials {
case .unauthenticated:
return eventLoop.makeSucceededFuture(())
case .auto(let username, let password):
if let mechanisms = serverHandshake!.saslSupportedMechs {
nextMechanism: for mechanism in mechanisms {
switch mechanism {
case "SCRAM-SHA-1":
return self.authenticateSASL(hasher: SHA1(), namespace: namespace, username: username, password: password)
case "SCRAM-SHA-256":
// TODO: Enforce minimum 4096 iterations
return self.authenticateSASL(hasher: SHA256(), namespace: namespace, username: username, password: password)
default:
continue nextMechanism
}
}
return eventLoop.makeFailedFuture(MongoAuthenticationError(reason: .unsupportedAuthenticationMechanism))
} else if serverHandshake!.maxWireVersion.supportsScramSha1 {
return self.authenticateSASL(hasher: SHA1(), namespace: namespace, username: username, password: password)
} else {
return self.authenticateCR(username, password: password, namespace: namespace)
}
case .scramSha1(let username, let password):
return self.authenticateSASL(hasher: SHA1(), namespace: namespace, username: username, password: password)
case .scramSha256(let username, let password):
return self.authenticateSASL(hasher: SHA256(), namespace: namespace, username: username, password: password)
case .mongoDBCR(let username, let password):
return self.authenticateCR(username, password: password, namespace: namespace)
}
}
public func selectAuthenticationAlgorithm(forUser user: String, password: String) throws -> ConnectionSettings.Authentication {
guard let handshake = serverHandshake else {
logger.error("Inferring the authentication mechanism failed. Missing handshake with the server")
throw MongoAuthenticationError(reason: .missingServerHandshake)
}
if let saslSupportedMechs = handshake.saslSupportedMechs {
nextMechanism: for mech in saslSupportedMechs {
switch mech {
case "SCRAM-SHA-256":
return .scramSha256(username: user, password: password)
case "SCRAM-SHA-1":
return .scramSha1(username: user, password: password)
default:
// Unknown algorithm
continue nextMechanism
}
}
}
if handshake.maxWireVersion.supportsScramSha1 {
return .scramSha1(username: user, password: password)
} else {
return .mongoDBCR(username: user, password: password)
}
}
}
| mit | 4387c1d7114f835b7384ac727b28d1e2 | 44.177215 | 132 | 0.612216 | 5.271787 | false | false | false | false |
groue/GRMustache.swift | Sources/ExpressionParser.swift | 2 | 18598 | // The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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
final class ExpressionParser {
func parse(_ string: String, empty outEmpty: inout Bool) throws -> Expression {
enum State {
// error
case error(String)
// Any expression can start
case waitingForAnyExpression
// Expression has started with a dot
case leadingDot
// Expression has started with an identifier
case identifier(identifierStart: String.Index)
// Parsing a scoping identifier
case scopingIdentifier(identifierStart: String.Index, baseExpression: Expression)
// Waiting for a scoping identifier
case waitingForScopingIdentifier(baseExpression: Expression)
// Parsed an expression
case doneExpression(expression: Expression)
// Parsed white space after an expression
case doneExpressionPlusWhiteSpace(expression: Expression)
}
var state: State = .waitingForAnyExpression
var filterExpressionStack: [Expression] = []
var i = string.startIndex
let end = string.endIndex
stringLoop: while i < end {
let c = string[i]
switch state {
case .error:
break stringLoop
case .waitingForAnyExpression:
switch c {
case " ", "\r", "\n", "\r\n", "\t":
break
case ".":
state = .leadingDot
case "(", ")", ",", "{", "}", "&", "$", "#", "^", "/", "<", ">":
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
default:
state = .identifier(identifierStart: i)
}
case .leadingDot:
switch c {
case " ", "\r", "\n", "\r\n", "\t":
state = .doneExpressionPlusWhiteSpace(expression: Expression.implicitIterator)
case ".":
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
case "(":
filterExpressionStack.append(Expression.implicitIterator)
state = .waitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: Expression.implicitIterator, partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: Expression.implicitIterator, partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
}
case "{", "}", "&", "$", "#", "^", "/", "<", ">":
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
default:
state = .scopingIdentifier(identifierStart: i, baseExpression: Expression.implicitIterator)
}
case .identifier(identifierStart: let identifierStart):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
let identifier = String(string[identifierStart..<i])
state = .doneExpressionPlusWhiteSpace(expression: Expression.identifier(identifier: identifier))
case ".":
let identifier = String(string[identifierStart..<i])
state = .waitingForScopingIdentifier(baseExpression: Expression.identifier(identifier: identifier))
case "(":
let identifier = String(string[identifierStart..<i])
filterExpressionStack.append(Expression.identifier(identifier: identifier))
state = .waitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = String(string[identifierStart..<i])
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: Expression.identifier(identifier: identifier), partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = String(string[identifierStart..<i])
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: Expression.identifier(identifier: identifier), partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
}
default:
break
}
case .scopingIdentifier(identifierStart: let identifierStart, baseExpression: let baseExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
let identifier = String(string[identifierStart..<i])
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
state = .doneExpressionPlusWhiteSpace(expression: scopedExpression)
case ".":
let identifier = String(string[identifierStart..<i])
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
state = .waitingForScopingIdentifier(baseExpression: scopedExpression)
case "(":
let identifier = String(string[identifierStart..<i])
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
filterExpressionStack.append(scopedExpression)
state = .waitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = String(string[identifierStart..<i])
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: scopedExpression, partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = String(string[identifierStart..<i])
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: scopedExpression, partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
}
default:
break
}
case .waitingForScopingIdentifier(let baseExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
state = .error("Unexpected white space character at index \(string.distance(from: string.startIndex, to: i))")
case ".":
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
case "(":
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
case ")":
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
case ",":
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
case "{", "}", "&", "$", "#", "^", "/", "<", ">":
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
default:
state = .scopingIdentifier(identifierStart: i, baseExpression: baseExpression)
}
case .doneExpression(let doneExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
state = .doneExpressionPlusWhiteSpace(expression: doneExpression)
case ".":
state = .waitingForScopingIdentifier(baseExpression: doneExpression)
case "(":
filterExpressionStack.append(doneExpression)
state = .waitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
}
default:
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
}
case .doneExpressionPlusWhiteSpace(let doneExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
break
case ".":
// Prevent "a .b"
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
case "(":
// Accept "a (b)"
filterExpressionStack.append(doneExpression)
state = .waitingForAnyExpression
case ")":
// Accept "a(b )"
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
}
case ",":
// Accept "a(b ,c)"
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
}
default:
state = .error("Unexpected character `\(c)` at index \(string.distance(from: string.startIndex, to: i))")
}
}
i = string.index(after: i)
}
// Parsing done
enum FinalState {
case error(String)
case empty
case valid(expression: Expression)
}
let finalState: FinalState
switch state {
case .waitingForAnyExpression:
if filterExpressionStack.isEmpty {
finalState = .empty
} else {
finalState = .error("Missing `)` character at index \(string.distance(from: string.startIndex, to: string.endIndex))")
}
case .leadingDot:
if filterExpressionStack.isEmpty {
finalState = .valid(expression: Expression.implicitIterator)
} else {
finalState = .error("Missing `)` character at index \(string.distance(from: string.startIndex, to: string.endIndex))")
}
case .identifier(identifierStart: let identifierStart):
if filterExpressionStack.isEmpty {
let identifier = String(string[identifierStart...])
finalState = .valid(expression: Expression.identifier(identifier: identifier))
} else {
finalState = .error("Missing `)` character at index \(string.distance(from: string.startIndex, to: string.endIndex))")
}
case .scopingIdentifier(identifierStart: let identifierStart, baseExpression: let baseExpression):
if filterExpressionStack.isEmpty {
let identifier = String(string[identifierStart...])
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
finalState = .valid(expression: scopedExpression)
} else {
finalState = .error("Missing `)` character at index \(string.distance(from: string.startIndex, to: string.endIndex))")
}
case .waitingForScopingIdentifier:
finalState = .error("Missing identifier at index \(string.distance(from: string.startIndex, to: string.endIndex))")
case .doneExpression(let doneExpression):
if filterExpressionStack.isEmpty {
finalState = .valid(expression: doneExpression)
} else {
finalState = .error("Missing `)` character at index \(string.distance(from: string.startIndex, to: string.endIndex))")
}
case .doneExpressionPlusWhiteSpace(let doneExpression):
if filterExpressionStack.isEmpty {
finalState = .valid(expression: doneExpression)
} else {
finalState = .error("Missing `)` character at index \(string.distance(from: string.startIndex, to: string.endIndex))")
}
case .error(let message):
finalState = .error(message)
}
// End
switch finalState {
case .empty:
outEmpty = true
throw MustacheError(kind: .parseError, message: "Missing expression")
case .error(let description):
outEmpty = false
throw MustacheError(kind: .parseError, message: "Invalid expression `\(string)`: \(description)")
case .valid(expression: let expression):
return expression
}
}
}
| mit | e3c00426a482c190ca772de0d5a4699c | 52.59366 | 200 | 0.54826 | 6.28277 | false | false | false | false |
ulukaya/firebase-ios-sdk | Example/Messaging/App/NotificationsController.swift | 1 | 4552 | /*
* Copyright 2017 Google
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import UserNotifications
import FirebaseDev
enum NotificationsControllerAllowedNotificationType: String {
case none = "None"
case silent = "Silent Updates"
case alert = "Alerts"
case badge = "Badges"
case sound = "Sounds"
}
let APNSTokenReceivedNotification: Notification.Name
= Notification.Name(rawValue: "APNSTokenReceivedNotification")
let UserNotificationsChangedNotification: Notification.Name
= Notification.Name(rawValue: "UserNotificationsChangedNotification")
class NotificationsController: NSObject {
static let shared: NotificationsController = {
let instance = NotificationsController()
return instance
}()
class func configure() {
let sharedController = NotificationsController.shared
// Always become the delegate of UNUserNotificationCenter, even before we've requested user
// permissions
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = sharedController
}
}
func registerForUserFacingNotificationsFor(_ application: UIApplication) {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .badge, .sound],
completionHandler: { (granted, error) in
NotificationCenter.default.post(name: UserNotificationsChangedNotification, object: nil)
})
} else if #available(iOS 8.0, *) {
let userNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound],
categories: [])
application.registerUserNotificationSettings(userNotificationSettings)
} else {
application.registerForRemoteNotifications(matching: [.alert, .badge, .sound])
}
}
func getAllowedNotificationTypes(_ completion:
@escaping (_ allowedTypes: [NotificationsControllerAllowedNotificationType]) -> Void) {
guard Messaging.messaging().apnsToken != nil else {
completion([.none])
return
}
var types: [NotificationsControllerAllowedNotificationType] = [.silent]
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings) in
if settings.alertSetting == .enabled {
types.append(.alert)
}
if settings.badgeSetting == .enabled {
types.append(.badge)
}
if settings.soundSetting == .enabled {
types.append(.sound)
}
DispatchQueue.main.async {
completion(types)
}
})
} else if #available(iOS 8.0, *) {
if let userNotificationSettings = UIApplication.shared.currentUserNotificationSettings {
if userNotificationSettings.types.contains(.alert) {
types.append(.alert)
}
if userNotificationSettings.types.contains(.badge) {
types.append(.badge)
}
if userNotificationSettings.types.contains(.sound) {
types.append(.sound)
}
}
completion(types)
} else {
let enabledTypes = UIApplication.shared.enabledRemoteNotificationTypes()
if enabledTypes.contains(.alert) {
types.append(.alert)
}
if enabledTypes.contains(.badge) {
types.append(.badge)
}
if enabledTypes.contains(.sound) {
types.append(.sound)
}
completion(types)
}
}
}
// MARK: - UNUserNotificationCenterDelegate
@available(iOS 10.0, *)
extension NotificationsController: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler:
@escaping (UNNotificationPresentationOptions) -> Void) {
// Always show the incoming notification, even if the app is in foreground
completionHandler([.alert, .badge, .sound])
}
}
| apache-2.0 | 861b82a655674d34b3829bb5eaa96f98 | 33.484848 | 99 | 0.675527 | 5.086034 | false | false | false | false |
zvonler/PasswordElephant | external/github.com/CryptoSwift/Sources/CryptoSwift/UInt8+Extension.swift | 5 | 2333 | //
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
#if canImport(Darwin)
import Darwin
#else
import Glibc
#endif
public protocol _UInt8Type {}
extension UInt8: _UInt8Type {}
/** casting */
extension UInt8 {
/** cast because UInt8(<UInt32>) because std initializer crash if value is > byte */
static func with(value: UInt64) -> UInt8 {
let tmp = value & 0xff
return UInt8(tmp)
}
static func with(value: UInt32) -> UInt8 {
let tmp = value & 0xff
return UInt8(tmp)
}
static func with(value: UInt16) -> UInt8 {
let tmp = value & 0xff
return UInt8(tmp)
}
}
/** Bits */
extension UInt8 {
init(bits: [Bit]) {
self.init(integerFrom(bits) as UInt8)
}
/** array of bits */
public func bits() -> [Bit] {
let totalBitsCount = MemoryLayout<UInt8>.size * 8
var bitsArray = [Bit](repeating: Bit.zero, count: totalBitsCount)
for j in 0..<totalBitsCount {
let bitVal: UInt8 = 1 << UInt8(totalBitsCount - 1 - j)
let check = self & bitVal
if check != 0 {
bitsArray[j] = Bit.one
}
}
return bitsArray
}
public func bits() -> String {
var s = String()
let arr: [Bit] = bits()
for idx in arr.indices {
s += (arr[idx] == Bit.one ? "1" : "0")
if idx.advanced(by: 1) % 8 == 0 { s += " " }
}
return s
}
}
| gpl-3.0 | f2d82c1264d4de1c1dd72663dce65719 | 29.684211 | 217 | 0.620926 | 3.925926 | false | false | false | false |
Google-IO-Extended-Grand-Rapids/conference_ios | ConferenceApp/ConferenceApp/ConferencesDao.swift | 1 | 2410 | //
// ConferencesDao.swift
// ConferenceApp
//
// Created by Dan McCracken on 3/7/15.
// Copyright (c) 2015 GR OpenSource. All rights reserved.
//
import Foundation
import ObjectMapper
class ConferencesDao {
let baseURL = "http://104.236.204.59:8080"
func makeRequestToAPI(url: String, onCompletion:(NSArray) -> ()) {
let realUrl = NSURL(string: url)
let request = NSURLRequest(URL: realUrl!)
let task : NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithRequest(request) {
(data, response, error) in
let json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as! NSArray
dispatch_async(dispatch_get_main_queue(), {
onCompletion(json)
})
}
task.resume()
}
func getAllConferences(conferenceHandler: (NSArray) -> ()) {
makeRequestToAPI(baseURL + "/api/conference") {
json in
var arrayOfConferenceObjects: [Conference] = []
if let conferenceArray = json as NSArray? {
for item in conferenceArray {
let conference = Mapper<Conference>().map(item)
arrayOfConferenceObjects.append(conference!)
}
}
conferenceHandler(arrayOfConferenceObjects)
}
}
func getSessionsByConferenceId(conferenceId: Int, sessionsHandler: (NSArray) -> ()) {
makeRequestToAPI(baseURL + "/api/conference/\(conferenceId)/conferenceSessions") {
json in
var arrayOfSessionObjects: [Session] = []
if let sessionsArray = json as NSArray? {
for item in sessionsArray {
let session = Mapper<Session>().map(item)
arrayOfSessionObjects.append(session!)
}
}
sessionsHandler(arrayOfSessionObjects)
}
}
func getConferenceById(conferenceId: Int, conferenceHandler: (Conference) -> ()) {
makeRequestToAPI(baseURL + "api/conference/\(conferenceId)") {
json in
let conference = Mapper<Conference>().map(json)
conferenceHandler(conference!)
}
}
} | apache-2.0 | 8af19132c1d2606dcce8482eab284de4 | 30.311688 | 120 | 0.553112 | 5.1606 | false | false | false | false |
zgtios/HQPhotoLock | PhotoLock/Controllers/PhotosCollectionViewController.swift | 2 | 34281 | //
// PhotosCollectionViewController.swift
// PhotoLock
//
// Created by 泉华 官 on 14/12/18.
// Copyright (c) 2014年 CQMH. All rights reserved.
//
import UIKit
let reuseIdentifier = "PhotoCollectionViewCell"
protocol PhotosCollectionViewControllerDelegate : class {
func setNeedReloadAlbumsTable()
}
class PhotosCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, CTAssetsPickerControllerDelegate, ImportPhotosFromFileSharingViewControllerDelegate {
// Veiws
@IBOutlet weak var collectionViewBottomMargin: NSLayoutConstraint!
@IBOutlet weak var importPhotoButtonItem: UIBarButtonItem!
@IBOutlet weak var hintImageView: UIImageView!
// MARK: - Vars
weak var delegate: PhotosCollectionViewControllerDelegate!
let defaultCellSize = CGSizeMake(70, 70)
var cellSize = CGSizeMake(70, 70)// 缩略图大小
var album: Album!
var photos: [AnyObject]! // 和photosSelected同时操作
var photosSelected: [Bool]!
var numPicturePerRow:Int = 4
var insectForCell: UIEdgeInsets!
var isNowEditing = false
var didReceiveMemoryWarnings = false
@IBOutlet weak var collectionView: UICollectionView!
// MARK: - View Did Load
override func viewDidLoad() {
super.viewDidLoad()
// 初始化
updateCellSizeAndCellInsect(view.bounds)
//
self.navigationController?.setToolbarHidden(true, animated: true)
// load album
let photosArrayObject: AnyObject? = DBMasterKey.findInTable(Photo.self, whereField: Photo.foreignKeys().first as! String, equalToValue: album.createdTime) as AnyObject?
photos = (photosArrayObject != nil ? (photosArrayObject as! [AnyObject]) : [])
photosSelected = [Bool]()
for i in 0..<photos.count {
photosSelected.append(false)
}
}
func updateCellSizeAndCellInsect(viewBound: CGRect) {
numPicturePerRow = Int(floor(viewBound.width / (defaultCellSize.width + 2.0)))
let w = ((viewBound.width + 2.0) / CGFloat(numPicturePerRow)) - 2.0
cellSize = CGSizeMake(w, w)
let insect = (viewBound.width - (CGFloat(numPicturePerRow) * w)) / (CGFloat(numPicturePerRow) - 1.0)
insectForCell = UIEdgeInsetsMake(insect, 0, 0, 0)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// 隐藏工具栏
if self.navigationController?.toolbarHidden == false {
self.navigationController?.setToolbarHidden(true, animated: true)
}
}
// MARK: - IBActions
@IBAction func addPhotos(sender: UIBarButtonItem) {
if !isNowEditing {
UIAlertView.showWithTitle(NSLocalizedString("Import Pictures", comment: ""),
message: NSLocalizedString("Please select where to import picture:", comment: ""),
cancelButtonTitle: NSLocalizedString("Cancel", comment: ""),
otherButtonTitles: [NSLocalizedString("iTunes file sharing", comment: ""), NSLocalizedString("Photos", comment: ""),],
tapBlock: {[unowned self] (alertView, index) -> Void in
if index == 1 {// iTunes file sharing fold
let importViewController = ImportPhotosFromFileSharingViewController()
importViewController.importDelegate = self
let importNavigationViewController = UINavigationController(rootViewController: importViewController)
self.presentViewController(importNavigationViewController, animated: true, completion: nil)
} else if index == 2 {// Photo albums
let pickerViewController = CTAssetsPickerController()
pickerViewController.delegate = self
pickerViewController.assetsFilter = ALAssetsFilter.allPhotos()
pickerViewController.showsCancelButton = true
pickerViewController.showsNumberOfAssets = true
pickerViewController.alwaysEnableDoneButton = true
self.presentViewController(pickerViewController, animated: true, completion: nil)
} else if index == 0 {
} else {
}
alertView.dismissWithClickedButtonIndex(index, animated: true)
})
}
}
@IBAction func editPhotos(sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizerState.Began {
isNowEditing = true
self.importPhotoButtonItem.enabled = false
self.navigationController?.setToolbarHidden(false, animated: true)
//
UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {[unowned self] () -> Void in
self.view.layoutIfNeeded()
}, completion: nil)
}
}
@IBAction func deleteSelectedPhotos(sender: UIBarButtonItem) {
var indexPaths = [NSIndexPath]()
var indexs = [Int]()
var photosToDelete = [Photo]()
for i in 0..<self.photos.count {
if self.photosSelected[i] {
indexs.insert(i, atIndex: 0)
let section = i / self.numPicturePerRow
let item = i % self.numPicturePerRow
indexPaths.append(NSIndexPath(forItem: item, inSection: section))
photosToDelete.append(self.photos[i] as! Photo)
}
}
// 未选择需要删除的照片,提示
if indexs.count == 0 {
let title = NSLocalizedString("Tip", comment: "")
let message = NSLocalizedString("Please select at least 1 picture!", comment: "")
let otherButtonsTitle = [NSLocalizedString("OK", comment: "")]
UIAlertView.showWithTitle(title,
message:message,
style: UIAlertViewStyle.Default,
cancelButtonTitle: nil,
otherButtonTitles: otherButtonsTitle) { (alertView, index) -> Void in
alertView.dismissWithClickedButtonIndex(index, animated: true)
}
return;
}
// 提示
let title = NSLocalizedString("Tip", comment: "")
let message = NSLocalizedString("Deleted pictures can not be recovered! Do you want to delete these pictures?", comment: "")
let cancelButtonTitle = NSLocalizedString("Cancel", comment: "")
let otherButtonsTitle = [NSLocalizedString("Delete", comment: "")]
UIAlertView.showWithTitle(title,
message:message,
style: UIAlertViewStyle.Default,
cancelButtonTitle: cancelButtonTitle,
otherButtonTitles: otherButtonsTitle) {[unowned self] (alertView, index) -> Void in
if index == 0 {
//
} else if index == 1 {
SVProgressHUD.showWithStatus(NSLocalizedString("Processing^_^", comment: ""))
let globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
dispatch_async(globalQueue, {[unowned self] () -> Void in
// 删除数据库中对应条目
DBMasterKey.deleteObjects(photosToDelete)
// 删除文件 原图+缩略图+占位图
let fileManager = NSFileManager.defaultManager()
var current = 0
for photo in photosToDelete {
if photo.originalFilename.hasSuffix(TiledSuffix) {
let imageBaseNameRowsColumnsWidthHeight = photo.originalFilename.componentsSeparatedByString("_")
let imageBaseName = imageBaseNameRowsColumnsWidthHeight[0]
let rows = imageBaseNameRowsColumnsWidthHeight[1].toInt()!
let columns = imageBaseNameRowsColumnsWidthHeight[2].toInt()!
for r in 0..<rows {
for c in 0..<columns {
let pathToTileImageFile = PictureFoldPath.stringByAppendingPathComponent(String(format: "%@%02i%02i", imageBaseName, c, r))
fileManager.removeItemAtPath(pathToTileImageFile, error: nil)
}
}
} else {
fileManager.removeItemAtPath(PictureFoldPath.stringByAppendingPathComponent(photo.originalFilename), error: nil)
}
fileManager.removeItemAtPath(ThumbnailFoldPath.stringByAppendingPathComponent(photo.thumbnailFilename), error: nil)
fileManager.removeItemAtPath(PlaceholderFoldPath.stringByAppendingPathComponent(photo.originalFilename + PlaceholderSuffix), error: nil)
current++
self.showProgress(current, total: photosToDelete.count)
}
// 删除collectionView数据源中对应条目
for i in indexs {
self.photos.removeAtIndex(i)
self.photosSelected.removeAtIndex(i)
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// 刷新视图
self.collectionView.reloadData()
// 显示处理完成
SVProgressHUD.showSuccessWithStatus(NSLocalizedString("Done", comment: ""))
})
})
}
alertView.dismissWithClickedButtonIndex(index, animated: true)
}
}
@IBAction func done(sender: UIBarButtonItem) {
// 将所有图片重置为未选择
for i in 0..<photosSelected.count {
if photosSelected[i] {
let section = i / self.numPicturePerRow
let item = i % self.numPicturePerRow
let cell = self.collectionView.cellForItemAtIndexPath(NSIndexPath(forItem: item, inSection: section))
cell?.alpha = 1.0
// 重置
photosSelected[i] = false
}
}
self.navigationController?.setToolbarHidden(true, animated: true)
//
collectionViewBottomMargin.constant = 0
UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {[unowned self] in
self.view.layoutIfNeeded()
}) {[unowned self] (finished) -> Void in
self.isNowEditing = false
self.importPhotoButtonItem.enabled = true
}
}
// MARK: - Funcitons
func imageWithImage(image:UIImage, scaledToFillSize size:CGSize) -> UIImage {
let scale = max(size.width / image.size.width, size.height / image.size.height)
let width = image.size.width * scale
let height = image.size.height * scale
let imageRect = CGRectMake((size.width - width) / 2.0, (size.height - height) / 2.0, width, height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
image.drawInRect(imageRect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
// MARK: - Rotation
override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
// ios 7
let version = (UIDevice.currentDevice().systemVersion as NSString).doubleValue
if version >= 7.0 && version < 8.0 {
self.adjustImageViews(self.view.bounds)
}
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
// ios 8 & later
let version = (UIDevice.currentDevice().systemVersion as NSString).doubleValue
if version >= 8.0 {
UIView.animateWithDuration(0.5, animations: {[unowned self] () -> Void in
self.adjustImageViews(CGRectMake(0, 0, size.width, size.height))
})
}
}
func adjustImageViews(viewBound: CGRect) {
self.updateCellSizeAndCellInsect(viewBound)
self.collectionView.reloadData()
}
// MARK: - Navigation
override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool {
return !isNowEditing
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == SegueIdentifierShowPhotos {
let indexPath = sender as! NSIndexPath
let destViewController = segue.destinationViewController as! PhotoDisplayViewController
destViewController.photos = photos
destViewController.currentPhotoIndex = indexPath.section * numPicturePerRow + indexPath.row
}
}
// MARK: UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
self.hintImageView.hidden = (photos.count != 0)
return Int(ceil(Float(photos.count) / Float(numPicturePerRow)))
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section * numPicturePerRow + numPicturePerRow > photos.count {
return photos.count - section * numPicturePerRow
} else {
return numPicturePerRow
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! UICollectionViewCell
let index = indexPath.section * numPicturePerRow + indexPath.row
let photo = photos[index] as! Photo
var thumbnailData = NSData(contentsOfFile: ThumbnailFoldPath.stringByAppendingPathComponent(photo.thumbnailFilename))
thumbnailData = thumbnailData?.decryptAndDcompress(thumbnailData)
let thumbnail = UIImage(data: thumbnailData!)
let imageView = cell.viewWithTag(2014) as! UIImageView
imageView.image = thumbnail ?? UIImage(named: "PHOTO64")
imageView.frame = cell.bounds
if photosSelected[index] {
cell.alpha = 0.3
} else {
cell.alpha = 1.0
}
return cell
}
// MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if isNowEditing {
let index = indexPath.section * numPicturePerRow + indexPath.row
photosSelected[index] = !photosSelected[index]
self.collectionView.cellForItemAtIndexPath(indexPath)?.alpha = photosSelected[index] ? 0.3 : 1.0
} else {
self.performSegueWithIdentifier(SegueIdentifierShowPhotos, sender: indexPath)
}
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return cellSize
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return self.insectForCell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return self.insectForCell.top
}
// MARK: - CTAssetsPickerControllerDelegate
func assetsPickerController(picker: CTAssetsPickerController!, didFinishPickingAssets assets: [AnyObject]!) {
// 用户没有选择图片时,提示用户
if assets.count == 0 {
let title = NSLocalizedString("Tip", comment: "")
let message = NSLocalizedString("Please select at least 1 picture!", comment: "")
let otherButtonsTitle = [NSLocalizedString("OK", comment: "")]
UIAlertView.showWithTitle(title,
message:message,
style: UIAlertViewStyle.Default,
cancelButtonTitle: nil,
otherButtonTitles: otherButtonsTitle) {(alertView, index) -> Void in
alertView.dismissWithClickedButtonIndex(index, animated: true)
}
return;
}
// 字符串格式化器
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
// 显示正在处理
SVProgressHUD.showProgress(0, status: NSLocalizedString("Processing^_^", comment: ""))
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
// 退出图片选择控制器
picker.dismissViewControllerAnimated(true, completion: {[unowned self] in
self.delegate.setNeedReloadAlbumsTable()
})
let globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
dispatch_async(globalQueue, {[unowned self] () -> Void in
// 获取已选图片->压缩&加密->复制到APP的文件夹目录->记录到数据库
var pictureData: NSData!
var buffer: UnsafeMutablePointer<UInt8>!
var index = 0
var errorOccours = false
var photo: Photo!
for asset in assets as! [ALAsset] {
if self.didReceiveMemoryWarnings {
errorOccours = true
break;
}
autoreleasepool({[unowned self] () -> () in
// 新建Photo对象
photo = Photo()
photo.createdTime = NSNumber(double: NSDate.timeIntervalSinceReferenceDate())
photo.name = dateFormatter.stringFromDate(asset.valueForProperty(ALAssetPropertyDate) as! NSDate)//用日期作为名称
photo.originalFilename = String(format: "%lf", photo.createdTime.doubleValue)
photo.thumbnailFilename = photo.originalFilename
photo.albumCreatedTime = self.album.createdTime
// 获取图片NSData
let representation = asset.defaultRepresentation()
let l = Int(representation.size())
buffer = UnsafeMutablePointer<UInt8>.alloc(l)
let length = representation.getBytes(buffer, fromOffset: 0, length: l, error: nil)
pictureData = NSData(bytes: buffer, length: length)
buffer.dealloc(l)
// 获取修正后的NSData
var originalImage = UIImage(data: pictureData)!
originalImage = UIImage.fixOrientation(originalImage)
pictureData = UIImagePNGRepresentation(originalImage)
let shouldDoLossyCompressionWhenSlicing = false
let imageBaseName = photo.originalFilename
// 获取图片大小
let imageSize = originalImage.size;
let results = self.importImage(pictureData, photo: photo, shouldDoLossyCompressionWhenSlicing: shouldDoLossyCompressionWhenSlicing, imageSize: imageSize)
// 检查是否成功保存文件
if results.success {
// 将数据写入数据库,添加到photos数组
if !DBMasterKey.add(photo) {
errorOccours = true
}
self.photos.append(photo)
self.photosSelected.append(false)
// 将所有需要保存的数据移到对应的文件夹
self.moveSavedFilesOfPhoto(photo, imageBaseName: imageBaseName, tilesCountVertical: results.tilesCountVertical, tilesCountHorizontal: results.tilesCountHorizontal)
} else {
errorOccours = true
}
})
index++
self.showProgress(index, total: assets.count)
}
// 确定该相册是否有icon,如果没有的话,将最后一张图片的缩略图作为相册icon
if self.album.icon == EmptyAlbumIconName {
self.album.icon = photo.thumbnailFilename
DBMasterKey.update(self.album)
}
// 若发生错误,(保存数据到数据库,或者保存图片到应用的文件夹下)时发生的错误, 提示用户
self.showUseTips(errorOccours)
})
}
func assetsPickerControllerDidCancel(picker: CTAssetsPickerController!) {
}
// MARK: - ImportPhotosFromFileSharingViewControllerDelegate
func importPhotosFromFileSharingViewController(importViewController: ImportPhotosFromFileSharingViewController, hasFinishedPickFiles files: [String]) {
// 显示正在处理
SVProgressHUD.showProgress(0, status: NSLocalizedString("Processing^_^", comment: ""))
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
// 退出图片选择控制器
importViewController.dismissViewControllerAnimated(true, completion: {[unowned self] () -> Void in
self.delegate.setNeedReloadAlbumsTable()
})
let globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
dispatch_async(globalQueue, {[unowned self] () -> Void in
// 获取已选图片->压缩&加密->复制到APP的文件夹目录->记录到数据库
var pictureData: NSData?
var index = 0
var photo: Photo!
var errorOccours = false
// 重置一下状态
self.didReceiveMemoryWarnings = false
for file in files {
if self.didReceiveMemoryWarnings {
errorOccours = true
break;
}
autoreleasepool({[unowned self] () -> () in
// 新建Photo对象
photo = Photo()
photo.createdTime = NSNumber(double: NSDate.timeIntervalSinceReferenceDate())
photo.name = "\(photo.createdTime.doubleValue)"
photo.originalFilename = String(format: "%lf", photo.createdTime.doubleValue)
photo.thumbnailFilename = photo.originalFilename
photo.albumCreatedTime = self.album.createdTime
// 获取图片NSData
let shouldDoLossyCompressionWhenSlicing = file.hasSuffix(".jpeg") || file.hasSuffix(".JPEG") || file.hasSuffix(".jpg") || file.hasSuffix(".JPG")
let imageBaseName = photo.originalFilename
// 获取图片大小
pictureData = NSData(contentsOfFile: file)
let imageSize = CQMHPhotoSlicer.imageSizeWithImageData(pictureData);
let results = self.importImage(pictureData, photo: photo, shouldDoLossyCompressionWhenSlicing: shouldDoLossyCompressionWhenSlicing, imageSize: imageSize)
// 检查是否成功保存文件
if results.success {
// 将数据写入数据库,添加到photos数组
if !DBMasterKey.add(photo) {
errorOccours = true
}
self.photos.append(photo)
self.photosSelected.append(false)
// 将所有需要保存的数据移到对应的文件夹
self.moveSavedFilesOfPhoto(photo, imageBaseName: imageBaseName, tilesCountVertical: results.tilesCountVertical, tilesCountHorizontal: results.tilesCountHorizontal)
// 删除文件
NSFileManager.defaultManager().removeItemAtPath(file, error: nil)
} else {
errorOccours = true
}
})
index++
self.showProgress(index, total: files.count)
}
// 确定该相册是否有icon,如果没有的话,将最后一张图片的缩略图作为相册icon
if self.album.icon == EmptyAlbumIconName {
self.album.icon = photo.thumbnailFilename
DBMasterKey.update(self.album)
}
// 若发生错误,(保存数据到数据库,或者保存图片到应用的文件夹下)时发生的错误, 提示用户
self.showUseTips(errorOccours)
})
}
// MARK: - Private
// 导入文件
func importImage(data: NSData?, photo: Photo!, shouldDoLossyCompressionWhenSlicing: Bool, imageSize: CGSize) -> (success:Bool, tilesCountHorizontal: Int?, tilesCountVertical: Int?) {
// 检查data是否为空
if data == nil {
return (false, 0, 0)
}
var placeholderProcessedOK: Bool = false
var pictureProcessedOK: Bool = false
var thumbnailProcessedOK: Bool = false
//
let fm = NSFileManager.defaultManager()
// 获取图片NSData
var pictureData = data!
// 获取缩略图NSData
let originalImage = UIImage(data: pictureData)!
let thumbnailImage = self.imageWithImage(originalImage, scaledToFillSize: self.cellSize)
var thumbnailData = UIImageJPEGRepresentation(thumbnailImage, 0.50)
if thumbnailData == nil {
thumbnailData = UIImagePNGRepresentation(thumbnailImage)
}
// 压缩加密缩略图
thumbnailData = thumbnailData.compressAndEncrypt(thumbnailData)
// 保存缩略图
if thumbnailData != nil {
thumbnailProcessedOK = fm.createFileAtPath(ThumbnailFoldPathTemp.stringByAppendingPathComponent(photo.thumbnailFilename),
contents: thumbnailData, attributes: nil)
}
// 如果分片的时候, 总共有多少分片
var tilesCountHorizontal: Int?// columns
var tilesCountVertical: Int?// rows
var imageBaseName = photo.originalFilename
// 判断是否分片
if imageSize.width * imageSize.height < MinPixelsForTiling {
// 压缩&加密原图
pictureData = pictureData.compressAndEncrypt(pictureData)
// 保存原图指定文件路径下
pictureProcessedOK = fm.createFileAtPath(PictureFoldPathTemp.stringByAppendingPathComponent(photo.originalFilename), contents: pictureData, attributes: nil)
// 占位图
var placeholderSize: CGSize!
if imageSize.width > imageSize.height {
placeholderSize = CGSizeMake(100.0, (100.0 / imageSize.width) * imageSize.height)
} else {
placeholderSize = CGSizeMake((100.0 / imageSize.height) * imageSize.width, 100.0)
}
let placeholderImage = self.imageWithImage(originalImage, scaledToFillSize: placeholderSize)
var placeholderData = UIImageJPEGRepresentation(placeholderImage, 0.30)
// 压缩加密
placeholderData = placeholderData.compressAndEncrypt(placeholderData)
// 保存占位图到指定文件路径下
placeholderProcessedOK = fm.createFileAtPath(PlaceholderFoldPathTemp.stringByAppendingPathComponent(photo.originalFilename + PlaceholderSuffix), contents: placeholderData, attributes: nil)
} else {// 占位图&分片
// 分片
let rowsColumns = CQMHPhotoSlicer.sliceImageData(pictureData, tileSize: TileSize, destinationFoldPath: PictureFoldPathTemp, tileImageBaseName: imageBaseName, shouldDoLossyCompression: shouldDoLossyCompressionWhenSlicing) as! [NSNumber]
tilesCountHorizontal = rowsColumns[1].integerValue
tilesCountVertical = rowsColumns[0].integerValue
pictureProcessedOK = (tilesCountHorizontal != 0 && tilesCountVertical != 0)
photo.originalFilename = photo.originalFilename.stringByAppendingFormat("_%d_%d_%lf_%lf_%@", tilesCountVertical!, tilesCountHorizontal!, imageSize.width, imageSize.height, TiledSuffix)// "filebasename_rows_columns_width_height_tiled"
// 占位图
var placeholderSize: CGSize!
if imageSize.width > imageSize.height {
placeholderSize = CGSizeMake(100.0, (100.0 / imageSize.width) * imageSize.height)
} else {
placeholderSize = CGSizeMake((100.0 / imageSize.height) * imageSize.width, 100.0)
}
let placeholderImage = self.imageWithImage(originalImage, scaledToFillSize: placeholderSize)
var placeholderData = UIImageJPEGRepresentation(placeholderImage, 0.0)
// 压缩加密
placeholderData = placeholderData.compressAndEncrypt(placeholderData)
// 保存占位图到指定文件路径下
placeholderProcessedOK = fm.createFileAtPath(PlaceholderFoldPathTemp.stringByAppendingPathComponent(photo.originalFilename + PlaceholderSuffix), contents: placeholderData, attributes: nil)
}
//
return (pictureProcessedOK && placeholderProcessedOK && thumbnailProcessedOK, tilesCountHorizontal, tilesCountVertical)
}
// 移动保存好的文件
func moveSavedFilesOfPhoto(photo: Photo!, imageBaseName:String?, tilesCountVertical: Int?, tilesCountHorizontal: Int?) {
let fm = NSFileManager.defaultManager()
// 将所有需要保存的数据移到对应的文件夹
// thumbnail
fm.moveItemAtPath(ThumbnailFoldPathTemp.stringByAppendingPathComponent(photo.thumbnailFilename), toPath: ThumbnailFoldPath.stringByAppendingPathComponent(photo.thumbnailFilename), error: nil)
// placeholder
fm.moveItemAtPath(PlaceholderFoldPathTemp.stringByAppendingPathComponent(photo.originalFilename + PlaceholderSuffix), toPath: PlaceholderFoldPath.stringByAppendingPathComponent(photo.originalFilename + PlaceholderSuffix), error: nil)
// 不分片,分片两种情况分别处理
if photo.originalFilename.hasSuffix(TiledSuffix) {
// original
for r in 0..<tilesCountVertical! {
for c in 0..<tilesCountHorizontal! {
let pictureFilename = String(format: "%@%02i%02i", imageBaseName!, c, r)
let pictureFilePath = PictureFoldPathTemp.stringByAppendingPathComponent(pictureFilename)
fm.moveItemAtPath(pictureFilePath, toPath: PictureFoldPath.stringByAppendingPathComponent(pictureFilename), error: nil)
}
}
} else {
// original
fm.moveItemAtPath(PictureFoldPathTemp.stringByAppendingPathComponent(photo.originalFilename), toPath: PictureFoldPath.stringByAppendingPathComponent(photo.originalFilename), error: nil)
}
}
// 显示进度
func showProgress(current: Int, total: Int) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
SVProgressHUD.showProgress(Float(current)/Float(total), status: NSLocalizedString("Processing^_^", comment: "") + "\(current)/\(total)")
})
}
// 显示用户提示
func showUseTips(errorOccours: Bool) {
if errorOccours {
dispatch_async(dispatch_get_main_queue(), {[unowned self] () -> Void in
SVProgressHUD.dismiss()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
self.collectionView.reloadData()
let title = NSLocalizedString("Tip", comment: "")
let messageKey = self.didReceiveMemoryWarnings ? "Some files are not imported! Please import them!" : "Error occurs"
let message = NSLocalizedString(messageKey, comment: "")
let otherButtonsTitle = [NSLocalizedString("OK", comment: "")]
UIAlertView.showWithTitle(title,
message:message,
style: UIAlertViewStyle.Default,
cancelButtonTitle: nil,
otherButtonTitles: otherButtonsTitle) { (alertView, index) -> Void in
alertView.dismissWithClickedButtonIndex(index, animated: true)
}
})
} else {
dispatch_async(dispatch_get_main_queue(), {[unowned self] () -> Void in
// 显示处理完成
SVProgressHUD.showSuccessWithStatus(NSLocalizedString("Done", comment: ""))
UIApplication.sharedApplication().endIgnoringInteractionEvents()
self.collectionView.reloadData()
})
}
}
// MARK: - Memory warning
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
didReceiveMemoryWarnings = true
}
}
| mit | 5042855f951766706c3a5b851e57d70d | 47.429619 | 247 | 0.602773 | 5.557631 | false | false | false | false |
tecgirl/firefox-ios | Storage/RemoteTabs.swift | 3 | 3699 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Deferred
public struct ClientAndTabs: Equatable, CustomStringConvertible {
public let client: RemoteClient
public let tabs: [RemoteTab]
public var description: String {
return "<Client guid: \(client.guid ?? "nil"), \(tabs.count) tabs.>"
}
// See notes in RemoteTabsPanel.swift.
public func approximateLastSyncTime() -> Timestamp {
if tabs.isEmpty {
return client.modified
}
return tabs.reduce(Timestamp(0), { m, tab in
return max(m, tab.lastUsed)
})
}
}
public func ==(lhs: ClientAndTabs, rhs: ClientAndTabs) -> Bool {
return (lhs.client == rhs.client) &&
(lhs.tabs == rhs.tabs)
}
public protocol RemoteClientsAndTabs: SyncCommands {
func wipeClients() -> Deferred<Maybe<()>>
func wipeRemoteTabs() -> Deferred<Maybe<()>>
func wipeTabs() -> Deferred<Maybe<()>>
func getClientGUIDs() -> Deferred<Maybe<Set<GUID>>>
func getClients() -> Deferred<Maybe<[RemoteClient]>>
func getClient(guid: GUID) -> Deferred<Maybe<RemoteClient?>>
func getClient(fxaDeviceId: String) -> Deferred<Maybe<RemoteClient?>>
func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>>
func getTabsForClientWithGUID(_ guid: GUID?) -> Deferred<Maybe<[RemoteTab]>>
func insertOrUpdateClient(_ client: RemoteClient) -> Deferred<Maybe<Int>>
func insertOrUpdateClients(_ clients: [RemoteClient]) -> Deferred<Maybe<Int>>
// Returns number of tabs inserted.
func insertOrUpdateTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>> // Insert into the local client.
func insertOrUpdateTabsForClientGUID(_ clientGUID: String?, tabs: [RemoteTab]) -> Deferred<Maybe<Int>>
func deleteClient(guid: GUID) -> Success
}
public struct RemoteTab: Equatable {
public let clientGUID: String?
public let URL: Foundation.URL
public let title: String
public let history: [Foundation.URL]
public let lastUsed: Timestamp
public let icon: Foundation.URL?
public static func shouldIncludeURL(_ url: Foundation.URL) -> Bool {
let scheme = url.scheme
if scheme == "about" {
return false
}
if scheme == "javascript" {
return false
}
if let hostname = url.host?.lowercased() {
if hostname == "localhost" {
return false
}
return true
}
return false
}
public init(clientGUID: String?, URL: Foundation.URL, title: String, history: [Foundation.URL], lastUsed: Timestamp, icon: Foundation.URL?) {
self.clientGUID = clientGUID
self.URL = URL
self.title = title
self.history = history
self.lastUsed = lastUsed
self.icon = icon
}
public func withClientGUID(_ clientGUID: String?) -> RemoteTab {
return RemoteTab(clientGUID: clientGUID, URL: URL, title: title, history: history, lastUsed: lastUsed, icon: icon)
}
}
public func ==(lhs: RemoteTab, rhs: RemoteTab) -> Bool {
return lhs.clientGUID == rhs.clientGUID &&
lhs.URL == rhs.URL &&
lhs.title == rhs.title &&
lhs.history == rhs.history &&
lhs.lastUsed == rhs.lastUsed &&
lhs.icon == rhs.icon
}
extension RemoteTab: CustomStringConvertible {
public var description: String {
return "<RemoteTab clientGUID: \(clientGUID ?? "nil"), URL: \(URL), title: \(title), lastUsed: \(lastUsed)>"
}
}
| mpl-2.0 | 486b0c562ea052ad2030b027156caffb | 33.570093 | 145 | 0.639632 | 4.5 | false | false | false | false |
mozilla-mobile/firefox-ios | Tests/UITests/LoginManagerTests.swift | 2 | 34471 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import Storage
@testable import Client
class LoginManagerTests: KIFTestCase {
fileprivate var webRoot: String!
override func setUp() {
super.setUp()
webRoot = SimplePageServer.start()
generateLogins()
BrowserUtils.dismissFirstRunUI(tester())
}
override func tearDown() {
super.tearDown()
clearLogins()
tester().wait(forTimeInterval: 5)
BrowserUtils.resetToAboutHomeKIF(tester())
}
fileprivate func openLoginManager() {
tester().waitForAnimationsToFinish(withTimeout: 3)
tester().tapView(withAccessibilityLabel: "Menu")
tester().tapView(withAccessibilityLabel: "Settings")
let firstIndexPath = IndexPath(row: 0, section: 1)
let list = tester().waitForView(withAccessibilityIdentifier: "AppSettingsTableViewController.tableView") as? UITableView
let row = tester().waitForCell(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "AppSettingsTableViewController.tableView")
tester().swipeView(withAccessibilityLabel: row?.accessibilityLabel, value: row?.accessibilityValue, in: KIFSwipeDirection.down)
tester().tapView(withAccessibilityIdentifier: "Logins")
}
fileprivate func closeLoginManager() {
tester().waitForAnimationsToFinish(withTimeout: 5)
tester().tapView(withAccessibilityLabel: "Settings")
tester().tapView(withAccessibilityIdentifier: "AppSettingsTableViewController.navigationItem.leftBarButtonItem")
}
fileprivate func generateLogins() {
let profile = (UIApplication.shared.delegate as! AppDelegate).profile!
let prefixes = "abcdefghijk"
let numRange = (0..<20)
let passwords = generateStringListWithFormat("password%@%d", numRange: numRange, prefixes: prefixes)
let hostnames = generateStringListWithFormat("http://%@%d.com", numRange: numRange, prefixes: prefixes)
let usernames = generateStringListWithFormat("%@%[email protected]", numRange: numRange, prefixes: prefixes)
(0..<(numRange.count * prefixes.count)).forEach { index in
var login = LoginRecord(fromJSONDict: [
"id": "\(index)",
"hostname": hostnames[index],
"username": usernames[index],
"password": passwords[index]
])
login.formSubmitUrl = hostnames[index]
_ = profile.logins.add(login: login).value
}
}
func waitForMatcher(name: String) {
tester().waitForAnimationsToFinish(withTimeout: 3)
tester().waitForView(withAccessibilityLabel: name)
tester().tapView(withAccessibilityLabel: name)
}
fileprivate func generateStringListWithFormat(_ format: String, numRange: CountableRange<Int>, prefixes: String) -> [String] {
return prefixes.map { char in
return numRange.map { num in
return String(format: format, "\(char)", num)
}
} .flatMap { $0 }
}
fileprivate func clearLogins() {
let profile = (UIApplication.shared.delegate as! AppDelegate).profile!
_ = profile.logins.wipeLocal().value
}
/* Temporary disabled due to a crash on BR
func testListFiltering() {
openLoginManager()
var list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView
// Filter by username
tester().waitForView(withAccessibilityLabel: "http://a0.com")
tester().waitForAnimationsToFinish()
tester().tapView(withAccessibilityLabel: "Filter")
tester().waitForAnimationsToFinish()
// In simulator, the typing is too fast for the screen to be updated properly
// pausing after 'password' (which all login password contains) to update the screen seems to make the test reliable
tester().enterText(intoCurrentFirstResponder: "k10")
tester().wait(forTimeInterval: 3) // Wait until the table is updated
tester().waitForAnimationsToFinish()
tester().enterText(intoCurrentFirstResponder: "@email.com")
tester().wait(forTimeInterval: 3) // Wait until the table is updated
tester().waitForAnimationsToFinish()
list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView
tester().waitForView(withAccessibilityLabel: "[email protected]")
tester().waitForAnimationsToFinish()
// Need to remove two cells for saveLogins identifier and showLoginsInAppMenu
let loginCount2 = countOfRowsInTableView(list) - 2
XCTAssertEqual(loginCount2, 1)
tester().tapView(withAccessibilityLabel: "Clear text")
// Filter by hostname
tester().waitForView(withAccessibilityLabel: "http://a0.com")
tester().tapView(withAccessibilityLabel: "Filter")
tester().waitForAnimationsToFinish()
tester().enterText(intoCurrentFirstResponder: "http://k10")
tester().waitForAnimationsToFinish()
tester().wait(forTimeInterval: 3) // Wait until the table is updated
tester().enterText(intoCurrentFirstResponder: ".com")
tester().wait(forTimeInterval: 3) // Wait until the table is updated
list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView
tester().waitForView(withAccessibilityLabel: "[email protected]")
// Need to remove two cells for saveLogins identifier and showLoginsInAppMenu
let loginCount1 = countOfRowsInTableView(list) - 2
XCTAssertEqual(loginCount1, 1)
tester().tapView(withAccessibilityLabel: "Clear text")
// Filter by something that doesn't match anything
tester().waitForView(withAccessibilityLabel: "http://a0.com")
tester().tapView(withAccessibilityLabel: "Filter")
tester().enterText(intoCurrentFirstResponder: "thisdoesntmatch")
tester().waitForView(withAccessibilityIdentifier: "Login List")
// KIFTest has a bug where waitForViewWithAccessibilityLabel causes the lists to appear again on device,
// so checking the number of rows instead
tester().waitForView(withAccessibilityLabel: "No logins found")
let loginCount = countOfRowsInTableView(list)
// Adding two to the count due to the new cells added
XCTAssertEqual(loginCount, 2)
tester().tapView(withAccessibilityLabel: "Cancel")
closeLoginManager()
}*/
func testListIndexView() {
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
openLoginManager()
// Swipe the index view to navigate to bottom section
tester().wait(forTimeInterval: 1)
tester().waitForView(withAccessibilityLabel: "[email protected]")
for _ in 1...6 {
tester().swipeView(withAccessibilityIdentifier: "SAVED LOGINS", in: KIFSwipeDirection.up)
}
tester().waitForAnimationsToFinish()
tester().waitForView(withAccessibilityLabel: "[email protected]")
closeLoginManager()
}
func testDetailPasswordMenuOptions() {
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
openLoginManager()
tester().waitForView(withAccessibilityLabel: "http://a0.com")
let firstIndexPath = IndexPath(row: 0, section: 1)
tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List")
tester().waitForView(withAccessibilityLabel: "Password")
var passwordField = tester().waitForView(withAccessibilityIdentifier: "passwordField") as! UITextField
XCTAssertTrue(passwordField.isSecureTextEntry)
// Tap the ‘Reveal’ menu option
let list2 = tester().waitForView(withAccessibilityIdentifier: "Login Detail List") as! UITableView
tester().tapRow(at: IndexPath(row: 3, section: 0), in: list2)
waitForMatcher(name: "Reveal")
passwordField = tester().waitForView(withAccessibilityIdentifier: "passwordField") as! UITextField
XCTAssertFalse(passwordField.isSecureTextEntry)
// Tap the ‘Hide’ menu option
tester().tapRow(at: IndexPath(row: 3, section: 0), in: list2)
waitForMatcher(name: "Hide")
passwordField = tester().waitForView(withAccessibilityIdentifier: "passwordField") as! UITextField
XCTAssertTrue(passwordField.isSecureTextEntry)
// Tap the ‘Copy’ menu option
tester().tapRow(at: IndexPath(row: 3, section: 0), in: list2)
waitForMatcher(name: "Copy")
tester().tapView(withAccessibilityLabel: "Logins & Passwords")
closeLoginManager()
XCTAssertEqual(UIPasteboard.general.string, "passworda0")
}
func testDetailWebsiteMenuCopy() {
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
openLoginManager()
tester().waitForView(withAccessibilityLabel: "http://a0.com")
let firstIndexPath = IndexPath(row: 0, section: 1)
tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List")
tester().waitForView(withAccessibilityLabel: "Password")
let list2 = tester().waitForView(withAccessibilityIdentifier: "Login Detail List") as! UITableView
tester().tapRow(at: IndexPath(row: 1, section: 0), in: list2)
waitForMatcher(name: "Copy")
// Tap the 'Open & Fill' menu option just checks to make sure we navigate to the web page
tester().tapRow(at: IndexPath(row: 1, section: 0), in: list2)
waitForMatcher(name: "Open & Fill")
tester().wait(forTimeInterval: 2)
tester().waitForViewWithAccessibilityValue("a0.com/")
XCTAssertEqual(UIPasteboard.general.string, "http://a0.com")
// Workaround
tester().tapView(withAccessibilityIdentifier: "TabToolbar.tabsButton")
tester().tapView(withAccessibilityIdentifier: AccessibilityIdentifiers.TabTray.closeAllTabsButton)
tester().tapView(withAccessibilityIdentifier: AccessibilityIdentifiers.TabTray.deleteCloseAllButton)
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
}
func testOpenAndFillFromNormalContext() {
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
openLoginManager()
tester().waitForView(withAccessibilityLabel: "http://a0.com")
let firstIndexPath = IndexPath(row: 0, section: 1)
tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List")
tester().waitForView(withAccessibilityLabel: "Password")
// Tap the 'Open & Fill' menu option just checks to make sure we navigate to the web page
let list2 = tester().waitForView(withAccessibilityIdentifier: "Login Detail List") as! UITableView
tester().tapRow(at: IndexPath(row: 1, section: 0), in: list2)
waitForMatcher(name: "Open & Fill")
tester().wait(forTimeInterval: 10)
tester().waitForViewWithAccessibilityValue("a0.com/")
// Workaround
tester().tapView(withAccessibilityIdentifier: "TabToolbar.tabsButton")
tester().tapView(withAccessibilityIdentifier: AccessibilityIdentifiers.TabTray.closeAllTabsButton)
tester().tapView(withAccessibilityIdentifier: AccessibilityIdentifiers.TabTray.deleteCloseAllButton)
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
}
// This test is disabled until bug 1486243 is fixed
/*func testOpenAndFillFromPrivateContext() {
if BrowserUtils.iPad() {
EarlGrey.selectElement(with: grey_accessibilityID("TopTabsViewController.tabsButton"))
.perform(grey_tap())
} else {
EarlGrey.selectElement(with: grey_accessibilityID("TabToolbar.tabsButton")).perform(grey_tap())
}
EarlGrey.selectElement(with: grey_accessibilityLabel("Private Mode")).perform(grey_tap())
EarlGrey.selectElement(with: grey_accessibilityLabel("Add Tab")).perform(grey_tap())
EarlGrey.selectElement(with: grey_accessibilityLabel("Menu")).perform(grey_tap())
if BrowserUtils.iPad() {
let settings_button = grey_allOf([grey_accessibilityLabel("Settings"),
grey_accessibilityID(ImageIdentifiers.settings)])
EarlGrey.selectElement(with: settings_button).perform(grey_tap())
} else {
EarlGrey.selectElement(with: grey_text("Settings")).perform(grey_tap())
}
if BrowserUtils.iPad() {
EarlGrey.selectElement(with: grey_accessibilityLabel("Tracking Protection"))
.using(searchAction: grey_scrollInDirection(.down, 200),
onElementWithMatcher: grey_accessibilityID("AppSettingsTableViewController.tableView"))
.assert(grey_notNil())
}
EarlGrey.selectElement(with: grey_accessibilityID("Logins")).perform(grey_tap())
tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com")
tester().tapView(withAccessibilityLabel: "[email protected], http://a0.com")
tester().waitForView(withAccessibilityLabel: "password")
// Tap the 'Open & Fill' menu option just checks to make sure we navigate to the web page
EarlGrey.selectElement(with: grey_accessibilityID("websiteField")).perform(grey_tap())
waitForMatcher(name: "Open & Fill")
tester().wait(forTimeInterval: 10)
tester().waitForViewWithAccessibilityValue("a0.com/")
}*/
func testDetailUsernameMenuOptions() {
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
openLoginManager()
tester().waitForView(withAccessibilityLabel: "http://a0.com")
let firstIndexPath = IndexPath(row: 0, section: 1)
tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List")
tester().waitForView(withAccessibilityLabel: "Password")
// Tap the 'Open & Fill' menu option just checks to make sure we navigate to the web page
let list2 = tester().waitForView(withAccessibilityIdentifier: "Login Detail List") as! UITableView
tester().tapRow(at: IndexPath(row: 2, section: 0), in: list2)
waitForMatcher(name: "Copy")
tester().tapView(withAccessibilityLabel: "Logins & Passwords")
closeLoginManager()
XCTAssertEqual(UIPasteboard.general.string!, "[email protected]")
}
func testListSelection() {
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
openLoginManager()
tester().waitForAnimationsToFinish()
tester().tapView(withAccessibilityLabel: "Edit")
tester().waitForAnimationsToFinish()
// Select one entry
let firstIndexPath = IndexPath(row: 0, section: 1)
tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List")
tester().waitForView(withAccessibilityLabel: "Delete")
let list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView
let firstCell = list.cellForRow(at: firstIndexPath)!
XCTAssertTrue(firstCell.isSelected)
// Deselect first row
tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List")
XCTAssertFalse(firstCell.isSelected)
// Cancel
tester().tapView(withAccessibilityLabel: "Cancel")
tester().waitForView(withAccessibilityLabel: "Edit")
// Select multiple logins
tester().tapView(withAccessibilityLabel: "Edit")
tester().waitForAnimationsToFinish()
let pathsToSelect = (0..<3).map { IndexPath(row: $0, section: 1) }
pathsToSelect.forEach { path in
tester().tapRow(at: path, inTableViewWithAccessibilityIdentifier: "Login List")
}
tester().waitForView(withAccessibilityLabel: "Delete")
pathsToSelect.forEach { path in
XCTAssertTrue(list.cellForRow(at: path)!.isSelected)
}
// Deselect only first row
tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List")
XCTAssertFalse(firstCell.isSelected)
// Make sure delete is still showing
tester().waitForView(withAccessibilityLabel: "Delete")
// Deselect the rest
let pathsWithoutFirst = pathsToSelect[1..<pathsToSelect.count]
pathsWithoutFirst.forEach { path in
tester().tapRow(at: path, inTableViewWithAccessibilityIdentifier: "Login List")
}
// Cancel
tester().tapView(withAccessibilityLabel: "Cancel")
tester().waitForView(withAccessibilityLabel: "Edit")
tester().tapView(withAccessibilityLabel: "Edit")
// Select all using select all button
tester().tapView(withAccessibilityLabel: "Select All")
// Now it is needed to scroll so the list is updated and the next assert works
tester().swipeView(withAccessibilityIdentifier: "SAVED LOGINS", in: KIFSwipeDirection.up)
tester().waitForAnimationsToFinish()
list.visibleCells.forEach { cell in
XCTAssertTrue(cell.isSelected)
}
tester().waitForView(withAccessibilityLabel: "Delete")
// Deselect all using button
tester().tapView(withAccessibilityLabel: "Deselect All")
list.visibleCells.forEach { cell in
XCTAssertFalse(cell.isSelected)
}
tester().tapView(withAccessibilityLabel: "Cancel")
tester().waitForView(withAccessibilityLabel: "Edit")
// Finally, test selections get persisted after cells recycle
tester().tapView(withAccessibilityLabel: "Edit")
let firstInEachSection = (0..<3).map { IndexPath(row: $0, section: 1) }
firstInEachSection.forEach { path in
tester().tapRow(at: path, inTableViewWithAccessibilityIdentifier: "Login List")
}
// Go up, down and back up to for some recycling
tester().scrollView(withAccessibilityIdentifier: "Login List", byFractionOfSizeHorizontal: 0, vertical: 1)
tester().scrollView(withAccessibilityIdentifier: "Login List", byFractionOfSizeHorizontal: 0, vertical: 1)
tester().scrollView(withAccessibilityIdentifier: "Login List", byFractionOfSizeHorizontal: 0, vertical: 1)
tester().wait(forTimeInterval: 1)
tester().waitForAnimationsToFinish()
XCTAssertTrue(list.cellForRow(at: firstInEachSection[0])!.isSelected)
firstInEachSection.forEach { path in
tester().tapRow(at: path, inTableViewWithAccessibilityIdentifier: "Login List")
}
tester().tapView(withAccessibilityLabel: "Cancel")
tester().waitForView(withAccessibilityLabel: "Edit")
closeLoginManager()
}
func testListSelectAndDelete() {
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
openLoginManager()
var list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView
let oldLoginCount = countOfRowsInTableView(list)
tester().tapView(withAccessibilityLabel: "Edit")
tester().waitForAnimationsToFinish()
// Select and delete one entry
let firstIndexPath = IndexPath(row: 0, section: 2)
tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List")
tester().waitForView(withAccessibilityLabel: "Delete")
let firstCell = list.cellForRow(at: firstIndexPath)!
XCTAssertTrue(firstCell.isSelected)
tester().tapView(withAccessibilityLabel: "Delete")
tester().waitForAnimationsToFinish()
tester().waitForView(withAccessibilityLabel: "Are you sure?")
tester().tapView(withAccessibilityLabel: "Delete")
tester().waitForAnimationsToFinish()
tester().waitForView(withAccessibilityLabel: "Settings")
tester().wait(forTimeInterval: 3) // Wait for the list to be updated
list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView
tester().wait(forTimeInterval: 3)
var newLoginCount = countOfRowsInTableView(list)
XCTAssertEqual(oldLoginCount - 1, newLoginCount)
// Select and delete multiple entries
tester().tapView(withAccessibilityLabel: "Edit")
tester().waitForAnimationsToFinish()
let multiplePaths = (0..<3).map { IndexPath(row: $0, section: 1) }
multiplePaths.forEach { path in
tester().tapRow(at: path, inTableViewWithAccessibilityIdentifier: "Login List")
}
tester().tapView(withAccessibilityLabel: "Delete")
tester().waitForAnimationsToFinish()
tester().waitForView(withAccessibilityLabel: "Are you sure?")
tester().tapView(withAccessibilityLabel: "Delete")
tester().waitForAnimationsToFinish()
tester().waitForView(withAccessibilityLabel: "Edit")
tester().wait(forTimeInterval: 1)
newLoginCount = countOfRowsInTableView(list)
XCTAssertEqual(oldLoginCount - 4, newLoginCount)
closeLoginManager()
}
func testSelectAllCancelAndEdit() {
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
openLoginManager()
tester().waitForView(withAccessibilityLabel: "Edit")
tester().waitForAnimationsToFinish()
tester().tapView(withAccessibilityLabel: "Edit")
// Select all using select all button
let list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView
tester().tapView(withAccessibilityLabel: "Select All")
// Now it is needed to scroll so the list is updated and the next assert works
tester().swipeView(withAccessibilityIdentifier: "SAVED LOGINS", in: KIFSwipeDirection.up)
tester().waitForAnimationsToFinish()
list.visibleCells.forEach { cell in
XCTAssertTrue(cell.isSelected)
}
tester().waitForView(withAccessibilityLabel: "Deselect All")
tester().tapView(withAccessibilityLabel: "Cancel")
tester().tapView(withAccessibilityLabel: "Edit")
// Make sure the state of the button is 'Select All' since we cancelled midway previously.
tester().waitForView(withAccessibilityLabel: "Select All")
tester().tapView(withAccessibilityLabel: "Cancel")
closeLoginManager()
}
/*
func testLoginListShowsNoResults() {
openLoginManager()
tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com")
let list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView
let oldLoginCount = countOfRowsInTableView(list)
// Find something that doesn't exist
tester().tapView(withAccessibilityLabel: "Enter Search Mode")
tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "")
tester().enterText(intoCurrentFirstResponder: "asdfasdf")
// KIFTest has a bug where waitForViewWithAccessibilityLabel causes the lists to appear again on device,
// so checking the number of rows instead
XCTAssertEqual(oldLoginCount, 220)
tester().waitForView(withAccessibilityLabel:"No logins found")
tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "")
// Erase search and make sure we see results instead
tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com")
closeLoginManager()
}
*/
fileprivate func countOfRowsInTableView(_ tableView: UITableView) -> Int {
var count = 0
(0..<tableView.numberOfSections).forEach { section in
count += tableView.numberOfRows(inSection: section)
}
return count
}
/**
This requires the software keyboard to display. Make sure 'Connect Hardware Keyboard' is off during testing.
Disabling since db crash is encountered due to a separate db bug
*/
/*
func testEditingDetailUsingReturnForNavigation() {
openLoginManager()
tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com")
tester().tapView(withAccessibilityLabel: "[email protected], http://a0.com")
tester().waitForView(withAccessibilityLabel: "password")
let list = tester().waitForView(withAccessibilityIdentifier: "Login Detail List") as! UITableView
tester().tapView(withAccessibilityLabel: "Edit")
// Check that we've selected the username field
var firstResponder = UIApplication.shared.keyWindow?.firstResponder()
let usernameCell = list.cellForRow(at: IndexPath(row: 1, section: 0)) as! LoginDetailTableViewCell
let usernameField = usernameCell.descriptionLabel
XCTAssertEqual(usernameField, firstResponder)
tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "changedusername")
tester().tapView(withAccessibilityLabel: "Next")
firstResponder = UIApplication.shared.keyWindow?.firstResponder()
let passwordCell = list.cellForRow(at: IndexPath(row: 2, section: 0)) as! LoginDetailTableViewCell
let passwordField = passwordCell.descriptionLabel
// Check that we've navigated to the password field upon return and that the password is no longer displaying as dots
XCTAssertEqual(passwordField, firstResponder)
XCTAssertFalse(passwordField.isSecureTextEntry)
tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "changedpassword")
tester().tapView(withAccessibilityLabel: "Done")
// Go back and find the changed login
tester().tapView(withAccessibilityLabel: "Back")
tester().tapView(withAccessibilityLabel: "Enter Search Mode")
tester().enterText(intoCurrentFirstResponder: "changedusername")
let loginsList = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView
XCTAssertEqual(loginsList.numberOfRows(inSection: 0), 1)
closeLoginManager()
}
*/
func testEditingDetailUpdatesPassword() {
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
openLoginManager()
tester().waitForView(withAccessibilityLabel: "http://a0.com")
let firstIndexPath = IndexPath(row: 0, section: 1)
tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List")
tester().waitForView(withAccessibilityLabel: "Password")
let list = tester().waitForView(withAccessibilityIdentifier: "Login Detail List") as! UITableView
tester().waitForAnimationsToFinish()
tester().tapView(withAccessibilityLabel: "Edit")
// Check that we've selected the username field
var firstResponder = UIApplication.shared.keyWindow?.firstResponder()
let usernameCell = list.cellForRow(at: IndexPath(row: 2, section: 0)) as! LoginDetailTableViewCell
let usernameField = usernameCell.descriptionLabel
XCTAssertEqual(usernameField, firstResponder)
tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "changedusername")
tester().tapView(withAccessibilityLabel: "next")
firstResponder = UIApplication.shared.keyWindow?.firstResponder()
var passwordCell = list.cellForRow(at: IndexPath(row: 3, section: 0)) as! LoginDetailTableViewCell
let passwordField = passwordCell.descriptionLabel
// Check that we've navigated to the password field upon return and that the password is no longer displaying as dots
XCTAssertEqual(passwordField, firstResponder)
XCTAssertFalse(passwordField.isSecureTextEntry)
tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "changedpassword")
tester().tapView(withAccessibilityLabel: "Done")
// Tap the 'Reveal' menu option
let list2 = tester().waitForView(withAccessibilityIdentifier: "Login Detail List") as! UITableView
tester().tapRow(at: IndexPath(row: 3, section: 0), in: list2)
waitForMatcher(name: "Reveal")
passwordCell = list.cellForRow(at: IndexPath(row: 3, section: 0)) as! LoginDetailTableViewCell
XCTAssertEqual(passwordCell.descriptionLabel.text, "changedpassword")
tester().tapView(withAccessibilityLabel: "Logins & Passwords")
closeLoginManager()
}
func testDeleteLoginFromDetailScreen() {
openLoginManager()
let list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView
let loginInitialCount = countOfRowsInTableView(list)
// Both the count and the first element is checked before removing
tester().wait(forTimeInterval: 3)
tester().waitForView(withAccessibilityIdentifier: "Login List")
let loginCountBeforeRemoving = countOfRowsInTableView(list)
XCTAssertEqual(loginCountBeforeRemoving, loginInitialCount)
let firstIndexPathBeforeRemoving = IndexPath(row: 0, section: 1)
// let firstCellBeforeRemoving = list.cellForRow(at: firstIndexPathBeforeRemoving)!
// let firstCellLabelBeforeRemoving = firstCellBeforeRemoving.textLabel?.text!
// XCTAssertEqual(firstCellLabelBeforeRemoving, "http://a0.com")
let firstIndexPath = IndexPath(row: 0, section: 1)
tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List")
tester().waitForAnimationsToFinish()
let list2 = tester().waitForView(withAccessibilityIdentifier: "Login Detail List") as! UITableView
tester().tapRow(at: IndexPath(row: 5, section: 0), in: list2)
tester().waitForAnimationsToFinish()
// Verify that we are looking at the nonsynced alert dialog
tester().waitForView(withAccessibilityLabel: "Are you sure?")
tester().waitForView(withAccessibilityLabel: "Logins will be removed from all connected devices.")
tester().tapView(withAccessibilityLabel: "Delete")
tester().waitForAnimationsToFinish()
// Check to verify that the element removed is not there
tester().waitForAbsenceOfView(withAccessibilityLabel: "http://a0.com")
tester().waitForView(withAccessibilityLabel: "http://a1.com")
// Both the count and the first element is checked before removing
let firstIndexPathAfterRemoving = IndexPath(row: 0, section: 1)
// let firstCellAfterRemoving = list.cellForRow(at: firstIndexPathAfterRemoving)!
// let firstCellLabelAfterRemoving = firstCellAfterRemoving.textLabel?.text!
// XCTAssertEqual(firstCellLabelAfterRemoving, "http://a1.com")
let loginCountAfterRemoving = countOfRowsInTableView(list)
XCTAssertEqual(loginCountAfterRemoving, loginInitialCount-1)
closeLoginManager()
}
func testLoginDetailDisplaysLastModified() {
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
openLoginManager()
tester().wait(forTimeInterval: 1)
tester().waitForView(withAccessibilityLabel: "http://a0.com")
let firstIndexPath = IndexPath(row: 0, section: 1)
tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List")
tester().waitForView(withAccessibilityLabel: "Password")
XCTAssertTrue(tester().viewExistsWithLabelPrefixedBy("Created just now"))
tester().wait(forTimeInterval: 1)
tester().tapView(withAccessibilityLabel: "Logins & Passwords")
closeLoginManager()
}
func testPreventBlankPasswordInDetail() {
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
openLoginManager()
tester().waitForAnimationsToFinish(withTimeout: 5)
tester().waitForView(withAccessibilityLabel: "http://a0.com")
let firstIndexPath = IndexPath(row: 0, section: 1)
tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List")
tester().waitForView(withAccessibilityLabel: "Password")
let list = tester().waitForView(withAccessibilityIdentifier: "Login Detail List") as! UITableView
tester().wait(forTimeInterval: 1)
tester().tapView(withAccessibilityLabel: "Edit")
// Check that we've selected the username field
tester().tapView(withAccessibilityIdentifier: "usernameField")
var passwordCell = list.cellForRow(at: IndexPath(row: 2, section: 0)) as! LoginDetailTableViewCell
var passwordField = passwordCell.descriptionLabel
tester().tapView(withAccessibilityLabel: "next")
tester().waitForAnimationsToFinish()
tester().clearTextFromView(withAccessibilityIdentifier: "passwordField")
tester().tapView(withAccessibilityLabel: "Done")
passwordCell = list.cellForRow(at: IndexPath(row: 3, section: 0)) as! LoginDetailTableViewCell
passwordField = passwordCell.descriptionLabel
// Confirm that when entering a blank password we revert back to the original
XCTAssertEqual(passwordField.text, "passworda0")
tester().tapView(withAccessibilityLabel: "Logins & Passwords")
closeLoginManager()
}
func testListEditButton() {
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
openLoginManager()
// Check that edit button is enabled when entries are present
tester().waitForView(withAccessibilityLabel: "Edit")
tester().tapView(withAccessibilityLabel: "Edit")
// Select all using select all button
tester().tapView(withAccessibilityLabel: "Select All")
// Delete all entries
tester().waitForView(withAccessibilityLabel: "Delete")
tester().tapView(withAccessibilityLabel: "Delete")
tester().waitForAnimationsToFinish()
tester().waitForView(withAccessibilityLabel: "Are you sure?")
tester().tapView(withAccessibilityLabel: "Delete")
tester().waitForAnimationsToFinish()
// Check that edit button has been disabled
tester().wait(forTimeInterval: 1)
tester().waitForView(withAccessibilityLabel: "Edit", traits: UIAccessibilityTraits.notEnabled)
closeLoginManager()
}
}
| mpl-2.0 | 41e24ec31ca911067c2bfdeae5a62af1 | 44.281209 | 142 | 0.690502 | 5.566882 | false | true | false | false |
futomtom/DynoOrder | Dyno/DynoOrder/RightMenuTableView.swift | 1 | 2843 | //
// SideMenuTableView.swift
// SideMenu
//
// Created by Jon Kent on 4/5/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import SideMenu
class RightMenuTableView: UITableViewController {
let order:Order! = nil
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! HeaderTableViewCell
headerCell.displayData(order: order)
return headerCell
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return order.itemList.count ?? 0
if let order = order {
return order.itemList.count
} else {
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ItemDetailCell
cell.displayData(item: order.itemList[indexPath.row])
return cell
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
}
}
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
}
| mit | ed5c19c229307ae2b2f49252d3346880 | 29.891304 | 136 | 0.641802 | 5.486486 | false | false | false | false |
aleph7/Surge | Upsurge.playground/Pages/Matrix Operations.xcplaygroundpage/Contents.swift | 2 | 526 | //: ## Matrix Arithmetic
//: This example shows how to perform basic matrix operations with Upsurge
import Upsurge
//: Let's define two matrices using row notation
let A = Matrix<Double>([
[1, 1],
[1, -1]
])
let C = Matrix<Double>([
[3],
[1]
])
//: Now let' find the matrix `B` such that `A*B=C`
let B = inv(A) * C
//: And verify the result
let r = A*B - C
//: You can also operate on a matrix row or column the same way as you would with a RealArray
var col = A.column(0)
let diff = col - [10, 1]
col += diff
| mit | b0b9e1600b6ee9f70122868264fb9363 | 25.3 | 93 | 0.634981 | 3.168675 | false | false | false | false |
kay-kim/stitch-examples | todo/ios/Pods/ExtendedJson/ExtendedJson/ExtendedJson/Source/Bson/Binary.swift | 1 | 969 | //
// BsonBinary.swift
// ExtendedJson
//
import Foundation
/// A representation of the BSON Binary type.
public struct Binary {
public private(set) var type: BsonBinarySubType
public private(set) var data: [UInt8]
public init(type: BsonBinarySubType = .binary, data: [UInt8]) {
self.type = type
self.data = data
}
}
// MARK: - Equatable
extension Binary: Equatable {
public static func ==(lhs: Binary, rhs: Binary) -> Bool {
return lhs.type == rhs.type && lhs.data == rhs.data
}
}
public enum BsonBinarySubType: UInt8 {
/// Binary data.
case binary = 0x00
/// A function.
case function = 0x01
/// Old binary.
case oldBinary = 0x02
/// A UUID in a driver dependent legacy byte order.
case uuidLegacy = 0x03
/// A UUID in standard network byte order.
case uuid = 0x04
/// MD5 Hash.
case md5 = 0x05
/// User defined binary data.
case userDefined = 0x80
}
| apache-2.0 | 696ba6517d73c757795aa0d63cab4dbd | 18.77551 | 67 | 0.625387 | 3.629213 | false | false | false | false |
bitjammer/swift | test/SILGen/collection_cast_crash.swift | 2 | 1980 | // RUN: %target-swift-frontend -O -Xllvm -sil-inline-generics=false -primary-file %s -emit-sil -o - | %FileCheck %s
// check if the compiler does not crash if a function is specialized
// which contains a collection cast
class MyClass {}
class KeyClass : Hashable {
var hashValue : Int { return 0 }
}
func ==(lhs: KeyClass, rhs: KeyClass) -> Bool { return true }
// CHECK-LABEL: sil hidden @{{.*}}arrayUpCast{{.*}} <Ct where Ct : MyClass>
func arrayUpCast<Ct: MyClass>(_ arr: [Ct]) -> [MyClass] {
// CHECK: apply %{{[0-9]*}}<Ct, MyClass>(%{{[0-9]*}})
return arr
// CHECK: return
}
// CHECK-LABEL: sil hidden @{{.*}}arrayDownCast{{.*}} <Ct where Ct : MyClass>
func arrayDownCast<Ct: MyClass>(_ arr: [MyClass]) -> [Ct] {
// CHECK: apply %{{[0-9]*}}<MyClass, Ct>(%{{[0-9]*}})
return arr as! [Ct]
// CHECK: return
}
// CHECK-LABEL: sil hidden @{{.*}}dictUpCast{{.*}} <Ct where Ct : MyClass>
func dictUpCast<Ct: MyClass>(_ dict: [KeyClass:Ct]) -> [KeyClass:MyClass] {
// CHECK: apply %{{[0-9]*}}<KeyClass, Ct, KeyClass, MyClass>(%{{[0-9]*}})
return dict as [KeyClass:MyClass]
// CHECK: return
}
// CHECK-LABEL: sil hidden @{{.*}}dictDownCast{{.*}} <Ct where Ct : MyClass>
func dictDownCast<Ct: MyClass>(_ dict: [KeyClass:MyClass]) -> [KeyClass:Ct] {
// CHECK: apply %{{[0-9]*}}<KeyClass, MyClass, KeyClass, Ct>(%{{[0-9]*}})
return dict as! [KeyClass:Ct]
// CHECK: return
}
func setUpCast<Ct: KeyClass>(_ s: Set<Ct>) -> Set<KeyClass> {
// CHECK: apply %{{[0-9]*}}<Ct, KeyClass>(%{{[0-9]*}})
return s as Set<KeyClass>
// CHECK: return
}
func setDownCast<Ct : KeyClass>(_ s : Set<KeyClass>) -> Set<Ct> {
// CHECK: apply %{{[0-9]*}}<KeyClass, Ct>(%{{[0-9]*}})
return s as! Set<Ct>
// CHECK: return
}
let arr: [MyClass] = [MyClass()]
arrayUpCast(arr)
arrayDownCast(arr)
let dict: [KeyClass:MyClass] = [KeyClass() : MyClass()]
dictUpCast(dict)
dictDownCast(dict)
let s: Set<KeyClass> = Set()
setUpCast(s)
setDownCast(s)
| apache-2.0 | 39fe0e34ec637b40a27c9d98ac6ec7e7 | 29 | 116 | 0.608586 | 3.041475 | false | false | false | false |
damoyan/BYRClient | FromScratch/ImageDecoder.swift | 1 | 5083 | //
// ImageDecoder.swift
// FromScratch
//
// Created by Yu Pengyang on 1/13/16.
// Copyright © 2016 Yu Pengyang. All rights reserved.
//
import UIKit
import ImageIO
protocol ImageDecoder {
var firstFrame: UIImage? { get }
var frameCount: Int { get }
var totalTime: NSTimeInterval { get }
func imageAtIndex(index: Int) -> UIImage?
func imageDurationAtIndex(index: Int) -> NSTimeInterval
}
class BYRImageDecoder: ImageDecoder {
private let scale: CGFloat
private let data: NSData
private var source: CGImageSource?
private var durations = [NSTimeInterval]()
var firstFrame: UIImage? = nil
var frameCount: Int = 0
var totalTime: NSTimeInterval = 0
init(data: NSData, scale: CGFloat = UIScreen.mainScreen().scale) {
self.data = data
self.scale = scale
source = CGImageSourceCreateWithData(data, nil)
generateImageInfo()
}
// MARK: - ImageDecoder
func imageAtIndex(index: Int) -> UIImage? {
guard let source = self.source else { return nil }
if let cgimage = CGImageSourceCreateImageAtIndex(source, index, nil) {
return decodeCGImage(cgimage, withScale: scale)
}
return nil
}
func imageDurationAtIndex(index: Int) -> NSTimeInterval {
guard index < durations.count else { return 0 }
/*
http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp
Many annoying ads specify a 0 duration to make an image flash as quickly as
possible. We follow Safari and Firefox's behavior and use a duration of 100 ms
for any frames that specify a duration of <= 10 ms.
See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information.
See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser.
*/
let duration = durations[index]
return duration < 0.011 ? 0.1 : duration
}
// MARK: - Private
private func generateImageInfo() {
guard let source = self.source else { return }
frameCount = CGImageSourceGetCount(source)
durations = [NSTimeInterval](count: frameCount, repeatedValue: 0)
for index in 0..<frameCount {
guard let properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) else {
continue
}
if index == 0, let cgimage = CGImageSourceCreateImageAtIndex(source, index, nil) {
firstFrame = decodeCGImage(cgimage, withScale: scale)
}
if let gifDict = getValue(properties, key: kCGImagePropertyGIFDictionary, type: CFDictionary.self) {
if let unclampedDelay = getValue(gifDict, key: kCGImagePropertyGIFUnclampedDelayTime, type: NSNumber.self) {
durations[index] = unclampedDelay.doubleValue
} else if let delay = getValue(gifDict, key: kCGImagePropertyGIFDelayTime, type: NSNumber.self) {
durations[index] = delay.doubleValue
}
}
}
}
// swift version of SDWebImage decoder (just copy code)
private func decodeCGImage(image: CGImage, withScale scale: CGFloat) -> UIImage? {
let imageSize = CGSize(width: CGImageGetWidth(image), height: CGImageGetHeight(image))
let imageRect = CGRect(origin: CGPointZero, size: imageSize)
let colorSpace = CGColorSpaceCreateDeviceRGB()
var bitmapInfo = CGImageGetBitmapInfo(image).rawValue
let infoMask = bitmapInfo & CGBitmapInfo.AlphaInfoMask.rawValue
let anyNonAlpha = (infoMask == CGImageAlphaInfo.None.rawValue ||
infoMask == CGImageAlphaInfo.NoneSkipFirst.rawValue ||
infoMask == CGImageAlphaInfo.NoneSkipLast.rawValue)
if infoMask == CGImageAlphaInfo.None.rawValue && CGColorSpaceGetNumberOfComponents(colorSpace) > 1 {
bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask.rawValue
bitmapInfo |= CGImageAlphaInfo.NoneSkipFirst.rawValue
} else if !anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3 {
bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask.rawValue
bitmapInfo |= CGImageAlphaInfo.PremultipliedFirst.rawValue
}
guard let context = CGBitmapContextCreate(nil, Int(imageSize.width), Int(imageSize.height), CGImageGetBitsPerComponent(image), 0, colorSpace, bitmapInfo) else { return nil }
CGContextDrawImage(context, imageRect, image)
guard let newImage = CGBitmapContextCreateImage(context) else { return nil }
return UIImage(CGImage: newImage, scale: scale, orientation: .Up)
}
private func getValue<T>(dict: CFDictionary, key: CFString, type: T.Type) -> T? {
let nkey = unsafeBitCast(key, UnsafePointer<Void>.self)
let v = CFDictionaryGetValue(dict, nkey)
if v == nil {
return nil
}
return unsafeBitCast(v, type)
}
} | mit | b383c7de85fe877fee113f46ad1d5dd4 | 41.358333 | 181 | 0.651318 | 4.849237 | false | false | false | false |
firebase/firebase-ios-sdk | FirebaseStorage/Sources/Internal/StorageTokenAuthorizer.swift | 1 | 4499 | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import FirebaseAppCheckInterop
import FirebaseAuthInterop
import FirebaseCore
@_implementationOnly import FirebaseCoreExtension
#if COCOAPODS
import GTMSessionFetcher
#else
import GTMSessionFetcherCore
#endif
internal class StorageTokenAuthorizer: NSObject, GTMSessionFetcherAuthorizer {
func authorizeRequest(_ request: NSMutableURLRequest?,
completionHandler handler: @escaping (Error?) -> Void) {
// Set version header on each request
let versionString = "ios/\(FirebaseVersion())"
request?.setValue(versionString, forHTTPHeaderField: "x-firebase-storage-version")
// Set GMP ID on each request
request?.setValue(googleAppID, forHTTPHeaderField: "x-firebase-gmpid")
var tokenError: NSError?
let callbackQueue = fetcherService.callbackQueue ?? DispatchQueue.main
let fetchTokenGroup = DispatchGroup()
if let auth = auth {
fetchTokenGroup.enter()
auth.getToken(forcingRefresh: false) { token, error in
if let error = error as? NSError {
var errorDictionary = error.userInfo
errorDictionary["ResponseErrorDomain"] = error.domain
errorDictionary["ResponseErrorCode"] = error.code
errorDictionary[NSLocalizedDescriptionKey] =
"User is not authenticated, please authenticate" +
" using Firebase Authentication and try again."
tokenError = NSError(domain: "FIRStorageErrorDomain",
code: StorageErrorCode.unauthenticated.rawValue,
userInfo: errorDictionary)
} else if let token = token {
let firebaseToken = "Firebase \(token)"
request?.setValue(firebaseToken, forHTTPHeaderField: "Authorization")
}
fetchTokenGroup.leave()
}
}
if let appCheck = appCheck {
fetchTokenGroup.enter()
appCheck.getToken(forcingRefresh: false) { tokenResult in
request?.setValue(tokenResult.token, forHTTPHeaderField: "X-Firebase-AppCheck")
if let error = tokenResult.error {
FirebaseLogger.log(
level: .debug,
service: "[FirebaseStorage]",
code: "I-STR000001",
message: "Failed to fetch AppCheck token. Error: \(error)"
)
}
fetchTokenGroup.leave()
}
}
fetchTokenGroup.notify(queue: callbackQueue) {
handler(tokenError)
}
}
func authorizeRequest(_ request: NSMutableURLRequest?, delegate: Any, didFinish sel: Selector) {
fatalError("Internal error: Should not call old authorizeRequest")
}
// Note that stopAuthorization, isAuthorizingRequest, and userEmail
// aren't relevant with the Firebase App/Auth implementation of tokens,
// and thus aren't implemented. Token refresh is handled transparently
// for us, and we don't allow the auth request to be stopped.
// Auth is also not required so the world doesn't stop.
func stopAuthorization() {}
func stopAuthorization(for request: URLRequest) {}
func isAuthorizingRequest(_ request: URLRequest) -> Bool {
return false
}
func isAuthorizedRequest(_ request: URLRequest) -> Bool {
guard let authHeader = request.allHTTPHeaderFields?["Authorization"] else {
return false
}
return authHeader.hasPrefix("Firebase")
}
var userEmail: String?
internal let fetcherService: GTMSessionFetcherService
private let googleAppID: String
private let auth: AuthInterop?
private let appCheck: AppCheckInterop?
private let serialAuthArgsQueue = DispatchQueue(label: "com.google.firebasestorage.authorizer")
init(googleAppID: String,
fetcherService: GTMSessionFetcherService,
authProvider: AuthInterop?,
appCheck: AppCheckInterop?) {
self.googleAppID = googleAppID
self.fetcherService = fetcherService
auth = authProvider
self.appCheck = appCheck
}
}
| apache-2.0 | 8dbb54a875560289565d4e3ddbab511f | 35.282258 | 98 | 0.698377 | 4.949395 | false | false | false | false |
pyro2927/PlexNotifier | PlexNotifier/PlexServerRequestManager.swift | 1 | 2324 | //
// PlexServerRequestManager.swift
// PlexNotifier
//
// Created by Joseph Pintozzi on 6/8/14.
// Copyright (c) 2014 pyro2927. All rights reserved.
//
import Cocoa
class PlexServerRequestManager: AFHTTPSessionManager {
init(baseURL url: NSURL!) {
super.init(baseURL: url, sessionConfiguration: nil)
responseSerializer = AFXMLDocumentResponseSerializer();
}
func setPlexToken(plexToken: String!) {
self.requestSerializer.setValue(plexToken, forHTTPHeaderField: "X-Plex-Token")
}
func getCurrentSessions() {
self.GET("/status/sessions", parameters: nil, success: {(sessionTask: NSURLSessionDataTask!, responseObject: AnyObject!) in
var xmlDocument: NSXMLDocument = responseObject as NSXMLDocument
let rootElement: NSXMLElement = xmlDocument.rootElement()
let videos: Array<NSXMLElement> = rootElement.children as Array<NSXMLElement>
for video: NSXMLElement in videos {
var videotitle = video.attributeForName("title").stringValue
if let grandparentTitle = video.attributeForName("grandparentTitle").stringValue {
videotitle = "\(grandparentTitle): \(videotitle)"
}
var username = "Unknown"
var player = ""
for child: NSXMLElement in video.children as Array<NSXMLElement> {
let childname: String = child.name
switch childname {
case "User":
println("Found user!")
username = child.attributeForName("title").stringValue
case "Player":
player = child.attributeForName("product").stringValue
default:
println("Not using this node")
}
}
let newNotification = NSUserNotification();
newNotification.title = "\(username) is watching \(videotitle)"
newNotification.subtitle = player
NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(newNotification)
}
}, failure: {(sessionTask: NSURLSessionDataTask!, error: NSError!) in
})
}
} | gpl-2.0 | 3c35f97a94a9b13a6189232689e1d8f2 | 41.272727 | 131 | 0.591652 | 5.52019 | false | false | false | false |
FandyLiu/FDDemoCollection | Swift/CitySelection/CitySelection/CityTableViewCell.swift | 1 | 4129 | //
// CityCollectionCell.swift
// CitySelection
//
// Created by QianTuFD on 2017/5/22.
// Copyright © 2017年 fandy. All rights reserved.
//
import UIKit
class FDCollectionViewFlowLayout: UICollectionViewFlowLayout {
init(_ colMargin: CGFloat, rowMargin: CGFloat, cols: Int, width: CGFloat, heigth: CGFloat) {
super.init()
minimumLineSpacing = rowMargin
minimumInteritemSpacing = colMargin
itemSize = CGSize(width: width, height: heigth)
sectionInset = UIEdgeInsets(top: rowMargin, left: colMargin, bottom: rowMargin, right: colMargin)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
protocol CityTableViewCellDelegate: NSObjectProtocol {
func cityTableViewCell(_ cityTableViewCell: CityTableViewCell, didSelectItemWith text: String)
}
class CityTableViewCell: UITableViewCell {
static let reuseIdentifier = "CityTableViewCellIdentifier"
private static let colMargin: CGFloat = 15
private static let rowMargin: CGFloat = 10
private static let cols: Int = 3
private static let width = (UIScreen.main.bounds.width - (colMargin * CGFloat(cols + 1))) / CGFloat(cols)
private static let height = width * 0.3
weak open var delegate: CityTableViewCellDelegate?
var cityArray = [String]() {
didSet {
collectionView.reloadData()
}
}
/// 计算collectionCell 高度
static func getCellHeight(_ cityArray: [String]) -> CGFloat {
let count = cityArray.count
let row = ceil(CGFloat(count) / CGFloat(cols))
return (row + 1) * rowMargin + row * height
}
/// collectionView
lazy var collectionView: UICollectionView = { [unowned self] in
let layout = FDCollectionViewFlowLayout(colMargin, rowMargin: rowMargin, cols: cols, width: width, heigth: height)
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.register(CityCollectionViewCell.self, forCellWithReuseIdentifier: CityCollectionViewCell.reuseIdentifier)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.bounces = false
collectionView.isScrollEnabled = false
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.backgroundColor = UIColor.white
return collectionView
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(collectionView)
let bindings = ["collectionView": collectionView]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[collectionView]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: bindings))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[collectionView]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: bindings))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension CityTableViewCell: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cityArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CityCollectionViewCell.reuseIdentifier, for: indexPath) as! CityCollectionViewCell
cell.text = cityArray[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.cityTableViewCell(self, didSelectItemWith: cityArray[indexPath.item])
}
}
| mit | 389667b4026d6fda52a2f321f160ba36 | 37.485981 | 171 | 0.707139 | 5.454305 | false | false | false | false |
cuba/NetworkKit | Source/Network/MockDispatcher.swift | 1 | 3668 | //
// MockDispatcher.swift
// NetworkKit iOS
//
// Created by Jacob Sikorski on 2019-03-31.
// Copyright © 2019 Jacob Sikorski. All rights reserved.
//
import Foundation
/// A mock dispatcher that does not actually make any network calls.
open class MockDispatcher: Dispatcher, ServerProvider {
open var mockData: Data?
open var mockStatusCode: StatusCode
open var mockHeaders: [String: String]
open var delay: TimeInterval = 0
public var baseURL: URL
func response(from request: Request) throws -> Response<Data?> {
let urlRequest = try self.urlRequest(from: request)
let statusCode = self.mockStatusCode
let headers = self.mockHeaders
let data = self.mockData
let url = urlRequest.url!
let error = self.mockStatusCode.makeError(cause: nil)
let httpResponse = HTTPURLResponse(url: url, statusCode: statusCode.rawValue, httpVersion: nil, headerFields: headers)!
let response = Response(data: data, httpResponse: httpResponse, urlRequest: urlRequest, statusCode: statusCode, error: error)
return response
}
/// Initialize this object with some mock data.
///
/// - Parameters:
/// - baseUrl: The base url that is used to construct the url on the response
/// - mockStatusCode: The status code to return
/// - mockError: The error to return (if any)
/// - mockHeaders: The headers that will be returned
public init(baseUrl: URL, mockStatusCode: StatusCode, mockHeaders: [String: String] = [:]) {
self.baseURL = baseUrl
self.mockStatusCode = mockStatusCode
self.mockHeaders = mockHeaders
}
/// Encode the object as a fake JSON response
///
/// - Parameter encodable: The object to encode into JSON
/// - Throws: Throws if the object cannot be encoded
public func setMockData<T: Encodable>(encodable: T) throws {
self.mockData = try JSONEncoder().encode(encodable)
}
/// Encode the object as a JSON response
///
/// - Parameters:
/// - jsonObject: The object to encode into JSON
/// - options: The encoding options
/// - Throws: Throws if the object cannot be encoded.
public func setMockData(jsonObject: [String: Any?], options: JSONSerialization.WritingOptions = []) throws {
self.mockData = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
}
/// Encode the object as a fake JSON response
///
/// - Parameters:
/// - jsonString: The string to encode
/// - encoding: The string encoding that will be used
public func setMockData(jsonString: String, encoding: String.Encoding = .utf8) {
self.mockData = jsonString.data(using: encoding)
}
/// Encode the object as a fake JSON response
///
/// - Parameter encodable: The object to encode into JSON
/// - Throws: Throws if the object cannot be encoded
public func setMockData<T: Encodable>(_ encodable: T) throws {
try setMockData(encodable: encodable)
}
/// Make a promise to send the request.
///
/// - Parameter request: The request to send.
/// - Returns: The promise that will send the request.
public func future(from request: Request) -> ResponseFuture<Response<Data?>> {
return ResponseFuture<Response<Data?>>() { promise in
let response = try self.response(from: request)
DispatchQueue.main.asyncAfter(deadline: .now() + self.delay) { // Change `2.0` to the desired
promise.succeed(with: response)
}
}
}
}
| mit | 11bf9c6070e9a7fe99b889b43a12afc4 | 37.6 | 133 | 0.646305 | 4.549628 | false | false | false | false |
almazrafi/Metatron | Tests/MetatronTests/ID3v1/ID3v1TagTrackNumberTest.swift | 1 | 8948 | //
// ID3v1TagTrackNumberTest.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
@testable import Metatron
class ID3v1TagTrackNumberTest: XCTestCase {
// MARK: Instance Methods
func test() {
let tag = ID3v1Tag()
do {
let value = TagNumber()
tag.trackNumber = value
do {
tag.version = ID3v1Version.v0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt1
XCTAssert(tag.toData() == nil)
}
}
do {
let value = TagNumber(999)
tag.trackNumber = value
do {
tag.version = ID3v1Version.v0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt1
XCTAssert(tag.toData() == nil)
}
}
do {
let value = TagNumber(0, total: 12)
tag.trackNumber = value
do {
tag.version = ID3v1Version.v0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt1
XCTAssert(tag.toData() == nil)
}
}
do {
let value = TagNumber(34, total: 12)
tag.trackNumber = value
do {
tag.version = ID3v1Version.v0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.v1
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.trackNumber == TagNumber(value.value))
}
do {
tag.version = ID3v1Version.vExt0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt1
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.trackNumber == TagNumber(value.value))
}
}
do {
let value = TagNumber(-12, total: 34)
tag.trackNumber = value
do {
tag.version = ID3v1Version.v0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt1
XCTAssert(tag.toData() == nil)
}
}
do {
let value = TagNumber(12, total: -34)
tag.trackNumber = value
do {
tag.version = ID3v1Version.v0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.v1
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.trackNumber == TagNumber(value.value))
}
do {
tag.version = ID3v1Version.vExt0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt1
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.trackNumber == TagNumber(value.value))
}
}
do {
let value = TagNumber(-12, total: -34)
tag.trackNumber = value
do {
tag.version = ID3v1Version.v0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt1
XCTAssert(tag.toData() == nil)
}
}
do {
let value = TagNumber(12)
tag.trackNumber = value
do {
tag.version = ID3v1Version.v0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.v1
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.trackNumber == TagNumber(value.value))
}
do {
tag.version = ID3v1Version.vExt0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt1
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.trackNumber == TagNumber(value.value))
}
}
do {
let value = TagNumber(12, total: 34)
tag.trackNumber = value
do {
tag.version = ID3v1Version.v0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.v1
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.trackNumber == TagNumber(value.value))
}
do {
tag.version = ID3v1Version.vExt0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt1
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.trackNumber == TagNumber(value.value))
}
}
}
}
| mit | 7252a8a11d1a39725eaf98dd2ce84e1a | 23.118598 | 81 | 0.451162 | 4.648312 | false | false | false | false |
nguyenantinhbk77/practice-swift | Games/JumpingBall/JumpingBall/GameScene.swift | 3 | 1711 | import SpriteKit
class GameScene: SKScene {
// Play button node
let playButton = SKSpriteNode(imageNamed: "play")
override func didMoveToView(view: SKView) {
// Position the play button in the middle of the screen
// It position the button in the middle of the frame.
self.playButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
// Add the button to the screen
self.addChild(self.playButton)
// Set the background color
self.backgroundColor = UIColor(hex: 0x809DFF)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch:AnyObject in touches{
// Grab the touch location
let location = touch.locationInNode(self)
// Retrieve the sprite in that location
// If the sprite at that location is matching play button, the do something!
if( self.nodeAtPoint(location) == self.playButton){
// Create a new PlayScene with the same size
let scene = PlayScene(size:self.size)
let view = self.view as SKView
// Ignore sibling order
view.ignoresSiblingOrder = true
// Scale mode for the new PlayScene
scene.scaleMode = .ResizeFill
// Set the scene size
scene.size = view.bounds.size
// Present the new scene
view.presentScene(scene)
}
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
| mit | 099acb59e32d3719075299f807b946d8 | 36.195652 | 100 | 0.578609 | 5.380503 | false | false | false | false |
evgenykarev/MapKit-and-UIKit-Examples | MapPoints/CLLocationCoordinate2D.swift | 1 | 1892 | //
// CLLocationCoordinate2D.swift
// MapPoints
//
// Created by Evgeny Karev on 12.05.17.
// Copyright © 2017 Evgeny Karev. All rights reserved.
//
import CoreLocation
extension CLLocationCoordinate2D: CustomStringConvertible {
/// Function converts float latitude or longitude value from Float to String according to ISO 6709
/**
- parameter floatValue: Float latitude or longitude value
- returns: String in ISO 6709 human readble format
*/
static func floatToDegrees(_ floatValue: Double) -> String {
let degrees = abs(floatValue.rounded(.towardZero))
var degreesPart = abs(floatValue) - degrees
let minutes = (degreesPart * 60).rounded(.towardZero)
degreesPart -= minutes / 60
let seconds = NSNumber(value: degreesPart * 3600)
let minutesFormatter = NumberFormatter()
minutesFormatter.minimumIntegerDigits = 2
let secondsFormatter = NumberFormatter()
secondsFormatter.numberStyle = .decimal
secondsFormatter.minimumIntegerDigits = 2
secondsFormatter.decimalSeparator = "."
secondsFormatter.maximumFractionDigits = 3
secondsFormatter.minimumFractionDigits = 3
return "\(Int(degrees))°\(minutesFormatter.string(from: NSNumber(value: minutes))!)′\(secondsFormatter.string(from: seconds)!)″"
}
public var latitudeString: String {
return "\(CLLocationCoordinate2D.floatToDegrees(latitude))\(latitude >= 0 ? "N" : "S")"
}
public var longitudeString: String {
return "\(CLLocationCoordinate2D.floatToDegrees(longitude))\(longitude >= 0 ? "E" : "W")"
}
/// Show coordinates in human readble format
/// ISO 6709 Annex D
/// https://en.wikipedia.org/wiki/ISO_6709
public var description: String {
return "\(latitudeString) \(longitudeString)"
}
}
| mit | 11ebf5c2a4083f0980b143488a57ab5e | 33.290909 | 136 | 0.670201 | 4.811224 | false | false | false | false |
DikeyKing/WeCenterMobile-iOS | WeCenterMobile/AppDelegate.swift | 1 | 3270 | //
// AppDelegate.swift
// WeCenterMobile
//
// Created by Darren Liu on 14/7/14.
// Copyright (c) 2014年 ifLab. All rights reserved.
//
import AFNetworking
import CoreData
import DTCoreText
import DTFoundation
import SinaWeiboSDK
import UIKit
import WeChatSDK
let userStrings: (String) -> String = {
return NSLocalizedString($0, tableName: "User", comment: "")
}
let discoveryStrings: (String) -> String = {
return NSLocalizedString($0, tableName: "Discovery", comment: "")
}
let welcomeStrings: (String) -> String = {
return NSLocalizedString($0, tableName: "Welcome", comment: "")
}
var appDelegate: AppDelegate {
return UIApplication.sharedApplication().delegate as! AppDelegate
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
lazy var window: UIWindow? = {
let v = UIWindow(frame: UIScreen.mainScreen().bounds)
return v
}()
lazy var loginViewController: LoginViewController = {
let vc = NSBundle.mainBundle().loadNibNamed("LoginViewController", owner: nil, options: nil).first as! LoginViewController
return vc
}()
var cacheFileURL: NSURL {
let directory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last as! NSURL
let url = directory.URLByAppendingPathComponent("WeCenterMobile.sqlite")
return url
}
var mainViewController: MainViewController!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
// clearCaches()
UIScrollView.msr_installPanGestureTranslationAdjustmentExtension()
UIScrollView.msr_installTouchesCancellingExtension()
AFNetworkActivityIndicatorManager.sharedManager().enabled = true
DTAttributedTextContentView.setLayerClass(DTTiledLayerWithoutFade.self)
WeiboSDK.registerApp("3758958382")
WXApi.registerApp("wx4dc4b980c462893b")
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateTheme", name: CurrentThemeDidChangeNotificationName, object: nil)
updateTheme()
window!.rootViewController = loginViewController
window!.makeKeyAndVisible()
return true
}
func applicationWillTerminate(application: UIApplication) {
NSNotificationCenter.defaultCenter().removeObserver(self)
DataManager.defaultManager!.saveChanges(nil)
}
func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
return WeiboSDK.handleOpenURL(url, delegate: nil) || WXApi.handleOpenURL(url, delegate: nil)
}
func clearCaches() {
NetworkManager.clearCookies()
NSFileManager.defaultManager().removeItemAtURL(cacheFileURL, error: nil)
DataManager.defaultManager = nil
DataManager.temporaryManager = nil
}
func updateTheme() {
let theme = SettingsManager.defaultManager.currentTheme
mainViewController?.contentViewController.view.backgroundColor = theme.backgroundColorA
UINavigationBar.appearance().barStyle = theme.navigationBarStyle
UINavigationBar.appearance().tintColor = theme.navigationItemColor
}
}
| gpl-2.0 | 63a6d09e8058db84fa4263c8a853fa3e | 34.521739 | 145 | 0.716646 | 5.296596 | false | false | false | false |
cruisediary/Diving | Diving/Scenes/TravelDetail/TravelDetailViewController.swift | 1 | 2799 |
//
// TravelDetailViewController.swift
// Diving
//
// Created by CruzDiary on 5/23/16.
// Copyright (c) 2016 DigitalNomad. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
protocol TravelDetailViewControllerInput {
func displaySomething(viewModel: TravelDetailViewModel)
}
protocol TravelDetailViewControllerOutput {
func doSomething(request: TravelDetailRequest)
func createTravel(request: TravelCreateForm)
}
class TravelDetailViewController: UIViewController, TravelDetailViewControllerInput {
var output: TravelDetailViewControllerOutput!
var router: TravelDetailRouter!
// MARK: Object lifecycle
let SHOW_DATE_PICKER_BOTTOM_CONSTRAINT_CONSTANT:CGFloat = 0
let HIDE_DATE_PICKER_BOTTOM_CONSTRAINT_CONSTANT:CGFloat = -256
let INPUT_VIEW_ANIMATION_DURATION:NSTimeInterval = 0.3
@IBOutlet weak var cancelButton: UIButton!
@IBAction func cancleButtonTap(sender: AnyObject) {
navigateToTravelList()
}
@IBOutlet weak var startDateChangeButton: UIButton!
@IBAction func startDateChangeButtonTap(sender: AnyObject) {
datePickerViewBottomConstraint.constant = SHOW_DATE_PICKER_BOTTOM_CONSTRAINT_CONSTANT
UIView.animateWithDuration(INPUT_VIEW_ANIMATION_DURATION) {
self.view.layoutIfNeeded()
}
}
@IBOutlet weak var endDateChangeButton: UIButton!
@IBAction func endDateChangeButtonTap(sender: AnyObject) {
}
@IBOutlet weak var datePickerView: UIView!
@IBOutlet weak var datePickerViewBottomConstraint: NSLayoutConstraint!
@IBAction func addTravelButtonTap(sender: AnyObject) {
output.createTravel(TravelCreateForm(
title: "유럽 여행", startDate: NSDate(), endDate: NSDate().dateByAddingTimeInterval(50000)
))
}
func navigateToTravelList() {
router.navigateToTravelListScene()
}
override func awakeFromNib() {
super.awakeFromNib()
TravelDetailConfigurator.sharedInstance.configure(self)
}
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
doSomethingOnLoad()
}
// MARK: Event handling
func doSomethingOnLoad() {
// NOTE: Ask the Interactor to do some work
let request = TravelDetailRequest()
output.doSomething(request)
}
// MARK: Display logic
func displaySomething(viewModel: TravelDetailViewModel) {
// NOTE: Display the result from the Presenter
// nameTextField.text = viewModel.name
}
}
| mit | b9e0ab7a8f154abb9f77d7c9d10cf958 | 27.773196 | 98 | 0.683268 | 4.975045 | false | false | false | false |
mervynokm/UIButton-ImageAndTitlePositioning | ButtonWithImageAndTitleExtension.swift | 1 | 5959 | //
// ButtonWithImageAndTitleExtension.swift
// ButtonWithImageAndTitleDemo
//
// Created by Mervyn Ong on 24/10/14.
// Copyright (c) 2014 mervynokm. All rights reserved.
//
//
// The MIT License (MIT)
//
// 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 UIKit
@objc extension UIButton {
/// Enum to determine the title position with respect to the button image
///
/// - top: title above button image
/// - bottom: title below button image
/// - left: title to the left of button image
/// - right: title to the right of button image
@objc enum Position: Int {
case top, bottom, left, right
}
/// This method sets an image and title for a UIButton and
/// repositions the titlePosition with respect to the button image.
///
/// - Parameters:
/// - image: Button image
/// - title: Button title
/// - titlePosition: UIViewContentModeTop, UIViewContentModeBottom, UIViewContentModeLeft or UIViewContentModeRight
/// - additionalSpacing: Spacing between image and title
/// - state: State to apply this behaviour
@objc func set(image: UIImage?, title: String, titlePosition: Position, additionalSpacing: CGFloat, state: UIControl.State){
imageView?.contentMode = .center
setImage(image, for: state)
setTitle(title, for: state)
titleLabel?.contentMode = .center
adjust(title: title as NSString, at: titlePosition, with: additionalSpacing)
}
/// This method sets an image and an attributed title for a UIButton and
/// repositions the titlePosition with respect to the button image.
///
/// - Parameters:
/// - image: Button image
/// - title: Button attributed title
/// - titlePosition: UIViewContentModeTop, UIViewContentModeBottom, UIViewContentModeLeft or UIViewContentModeRight
/// - additionalSpacing: Spacing between image and title
/// - state: State to apply this behaviour
@objc func set(image: UIImage?, attributedTitle title: NSAttributedString, at position: Position, width spacing: CGFloat, state: UIControl.State){
imageView?.contentMode = .center
setImage(image, for: state)
adjust(attributedTitle: title, at: position, with: spacing)
titleLabel?.contentMode = .center
setAttributedTitle(title, for: state)
}
// MARK: Private Methods
@objc private func adjust(title: NSString, at position: Position, with spacing: CGFloat) {
let imageRect: CGRect = self.imageRect(forContentRect: frame)
// Use predefined font, otherwise use the default
let titleFont: UIFont = titleLabel?.font ?? UIFont()
let titleSize: CGSize = title.size(withAttributes: [NSAttributedString.Key.font: titleFont])
arrange(titleSize: titleSize, imageRect: imageRect, atPosition: position, withSpacing: spacing)
}
@objc private func adjust(attributedTitle: NSAttributedString, at position: Position, with spacing: CGFloat) {
let imageRect: CGRect = self.imageRect(forContentRect: frame)
let titleSize = attributedTitle.size()
arrange(titleSize: titleSize, imageRect: imageRect, atPosition: position, withSpacing: spacing)
}
@objc private func arrange(titleSize: CGSize, imageRect:CGRect, atPosition position: Position, withSpacing spacing: CGFloat) {
switch (position) {
case .top:
titleEdgeInsets = UIEdgeInsets(top: -(imageRect.height + titleSize.height + spacing), left: -(imageRect.width), bottom: 0, right: 0)
imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
contentEdgeInsets = UIEdgeInsets(top: spacing / 2 + titleSize.height, left: -imageRect.width/2, bottom: 0, right: -imageRect.width/2)
case .bottom:
titleEdgeInsets = UIEdgeInsets(top: (imageRect.height + titleSize.height + spacing), left: -(imageRect.width), bottom: 0, right: 0)
imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
contentEdgeInsets = UIEdgeInsets(top: 0, left: -imageRect.width/2, bottom: spacing / 2 + titleSize.height, right: -imageRect.width/2)
case .left:
titleEdgeInsets = UIEdgeInsets(top: 0, left: -(imageRect.width * 2), bottom: 0, right: 0)
imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -(titleSize.width * 2 + spacing))
contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: spacing / 2)
case .right:
titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -spacing)
imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: spacing / 2)
}
}
}
| mit | ec4f47d87fdffa6699431d2f35f2c973 | 48.247934 | 150 | 0.677798 | 4.535008 | false | false | false | false |
Swift3Home/Swift3_Object-oriented | 018-计算型属性/018-计算型属性/ViewController.swift | 1 | 928 | //
// ViewController.swift
// 018-计算型属性
//
// Created by lichuanjun on 2017/6/7.
// Copyright © 2017年 lichuanjun. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private lazy var p = TLPerson()
override func viewDidLoad() {
super.viewDidLoad()
// let p = TLPerson()
// setter
p.name = "老王"
// getter
print(p.name ?? "")
print(p.title)
// Cannot assign to property: 'title' is a get-only property
// 不能给 get-only 属性设置值
// p.title = "XXX"
// 不允许修改只读属性
// p.title2 = "XXX"
print(p.title2)
print(p.title3)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
p.name = "花花"
print(p.title2)
print(p.title3)
}
}
| mit | 2af45c0d86928d9896755115dcdbdf45 | 18.840909 | 79 | 0.521191 | 3.577869 | false | false | false | false |
JGiola/swift | validation-test/stdlib/UnicodeScalarProperties.swift | 1 | 9726 | // RUN: %target-run-simple-swift %S/../../utils/gen-unicode-data/Data/
// REQUIRES: executable_test
// REQUIRES: long_test
// REQUIRES: optimized_stdlib
// REQUIRES: objc_interop
@_spi(_Unicode)
import Swift
import StdlibUnittest
import StdlibUnicodeUnittest
var UnicodeScalarPropertiesTest = TestSuite("UnicodeScalarProperties")
//===----------------------------------------------------------------------===//
// Binary Properties
//===----------------------------------------------------------------------===//
if #available(SwiftStdlib 5.6, *) {
UnicodeScalarPropertiesTest.test("Binary Properties") {
// First, check that we correctly parsed the unicode data tables to be able
// to test against.
// We have 48 properties, but some properties have 'Other_' properties which
// are included in them, so count those as well.
expectEqual(56, binaryProperties.keys.count)
for i in 0x0 ... 0x10FFFF {
guard let scalar = Unicode.Scalar(i) else {
continue
}
func check(_ property: String) -> Bool {
binaryProperties[property]!.contains(scalar)
}
let props = scalar.properties
expectEqual(props.isAlphabetic, check("Alphabetic") || check("Other_Alphabetic"))
expectEqual(props.isASCIIHexDigit, check("ASCII_Hex_Digit"))
expectEqual(props.isBidiControl, check("Bidi_Control"))
expectEqual(props.isBidiMirrored, check("Bidi_Mirrored"))
expectEqual(props.isCased, check("Cased"))
expectEqual(props.isCaseIgnorable, check("Case_Ignorable"))
expectEqual(props.changesWhenCaseFolded, check("Changes_When_Casefolded"))
expectEqual(props.changesWhenCaseMapped, check("Changes_When_Casemapped"))
expectEqual(props.changesWhenLowercased, check("Changes_When_Lowercased"))
expectEqual(props.changesWhenNFKCCaseFolded, check("Changes_When_NFKC_Casefolded"))
expectEqual(props.changesWhenTitlecased, check("Changes_When_Titlecased"))
expectEqual(props.changesWhenUppercased, check("Changes_When_Uppercased"))
expectEqual(props.isDash, check("Dash"))
expectEqual(props.isDefaultIgnorableCodePoint, check("Default_Ignorable_Code_Point") || check("Other_Default_Ignorable_Code_Point"))
expectEqual(props.isDeprecated, check("Deprecated"))
expectEqual(props.isDiacritic, check("Diacritic"))
expectEqual(props.isEmoji, check("Emoji"))
expectEqual(props.isEmojiModifier, check("Emoji_Modifier"))
expectEqual(props.isEmojiModifierBase, check("Emoji_Modifier_Base"))
expectEqual(props.isEmojiPresentation, check("Emoji_Presentation"))
expectEqual(props.isExtender, check("Extender"))
expectEqual(props.isFullCompositionExclusion, check("Full_Composition_Exclusion"))
expectEqual(props.isGraphemeBase, check("Grapheme_Base"))
expectEqual(props.isGraphemeExtend, check("Grapheme_Extend") || check("Other_Grapheme_Extend"))
expectEqual(props.isHexDigit, check("Hex_Digit"))
expectEqual(props.isIDContinue, check("ID_Continue") || check("Other_ID_Continue"))
expectEqual(props.isIDStart, check("ID_Start") || check("Other_ID_Start"))
expectEqual(props.isIdeographic, check("Ideographic"))
expectEqual(props.isIDSBinaryOperator, check("IDS_Binary_Operator"))
expectEqual(props.isIDSTrinaryOperator, check("IDS_Trinary_Operator"))
expectEqual(props.isJoinControl, check("Join_Control"))
expectEqual(props.isLogicalOrderException, check("Logical_Order_Exception"))
expectEqual(props.isLowercase, check("Lowercase") || check("Other_Lowercase"))
expectEqual(props.isMath, check("Math") || check("Other_Math"))
expectEqual(props.isNoncharacterCodePoint, check("Noncharacter_Code_Point"))
expectEqual(props.isPatternSyntax, check("Pattern_Syntax"))
expectEqual(props.isPatternWhitespace, check("Pattern_White_Space"))
expectEqual(props.isQuotationMark, check("Quotation_Mark"))
expectEqual(props.isRadical, check("Radical"))
expectEqual(props.isSentenceTerminal, check("Sentence_Terminal"))
expectEqual(props.isSoftDotted, check("Soft_Dotted"))
expectEqual(props.isTerminalPunctuation, check("Terminal_Punctuation"))
expectEqual(props.isUnifiedIdeograph, check("Unified_Ideograph"))
expectEqual(props.isUppercase, check("Uppercase") || check("Other_Uppercase"))
expectEqual(props.isVariationSelector, check("Variation_Selector"))
expectEqual(props.isWhitespace, check("White_Space"))
expectEqual(props.isXIDContinue, check("XID_Continue"))
expectEqual(props.isXIDStart, check("XID_Start"))
}
}
}
//===----------------------------------------------------------------------===//
// Numeric Properties
//===----------------------------------------------------------------------===//
if #available(SwiftStdlib 5.6, *) {
UnicodeScalarPropertiesTest.test("Numeric Properties") {
for i in 0x0 ... 0x10FFFF {
guard let scalar = Unicode.Scalar(i) else {
continue
}
expectEqual(scalar.properties.numericType, numericTypes[scalar])
expectEqual(scalar.properties.numericValue, numericValues[scalar])
}
}
}
//===----------------------------------------------------------------------===//
// Scalar Mappings
//===----------------------------------------------------------------------===//
if #available(SwiftStdlib 5.6, *) {
UnicodeScalarPropertiesTest.test("Scalar Mappings") {
for i in 0x0 ... 0x10FFFF {
guard let scalar = Unicode.Scalar(i) else {
continue
}
if let upper = mappings[scalar]?["upper"] {
expectEqual(scalar.properties.uppercaseMapping, upper)
}
if let lower = mappings[scalar]?["lower"] {
expectEqual(scalar.properties.lowercaseMapping, lower)
}
if let title = mappings[scalar]?["title"] {
expectEqual(scalar.properties.titlecaseMapping, title)
}
}
}
}
//===----------------------------------------------------------------------===//
// Scalar Age
//===----------------------------------------------------------------------===//
if #available(SwiftStdlib 5.6, *) {
UnicodeScalarPropertiesTest.test("Scalar Age") {
for i in 0x0 ... 0x10FFFF {
guard let scalar = Unicode.Scalar(i) else {
continue
}
expectEqual(scalar.properties.age?.major, ages[scalar]?.major)
expectEqual(scalar.properties.age?.minor, ages[scalar]?.minor)
}
}
}
//===----------------------------------------------------------------------===//
// Scalar General Category
//===----------------------------------------------------------------------===//
if #available(SwiftStdlib 5.6, *) {
UnicodeScalarPropertiesTest.test("Scalar General Category") {
for i in 0x0 ... 0x10FFFF {
guard let scalar = Unicode.Scalar(i) else {
continue
}
expectEqual(scalar.properties.generalCategory, generalCategories[scalar])
}
}
}
//===----------------------------------------------------------------------===//
// Scalar Name Alias
//===----------------------------------------------------------------------===//
if #available(SwiftStdlib 5.6, *) {
UnicodeScalarPropertiesTest.test("Scalar Name Alias") {
for i in 0x0 ... 0x10FFFF {
guard let scalar = Unicode.Scalar(i) else {
continue
}
expectEqual(scalar.properties.nameAlias, nameAliases[scalar])
}
}
}
//===----------------------------------------------------------------------===//
// Scalar Name
//===----------------------------------------------------------------------===//
if #available(SwiftStdlib 5.6, *) {
UnicodeScalarPropertiesTest.test("Scalar Name") {
for i in 0x0 ... 0x10FFFF {
guard let scalar = Unicode.Scalar(i) else {
continue
}
expectEqual(scalar.properties.name, names[scalar])
}
}
}
//===----------------------------------------------------------------------===//
// Case Folded
//===----------------------------------------------------------------------===//
if #available(SwiftStdlib 5.7, *) {
UnicodeScalarPropertiesTest.test("Scalar Case Folding") {
for i in 0x0 ... 0x10FFFF {
guard let scalar = Unicode.Scalar(i) else {
continue
}
if let mapping = caseFolding[scalar] {
expectEqual(scalar.properties._caseFolded, mapping)
} else {
expectEqual(scalar.properties._caseFolded, String(scalar))
}
}
}
}
//===----------------------------------------------------------------------===//
// Script/Script Extensions
//===----------------------------------------------------------------------===//
if #available(SwiftStdlib 5.7, *) {
UnicodeScalarPropertiesTest.test("Scalar Scripts") {
for i in 0x0 ... 0x10FFFF {
guard let scalar = Unicode.Scalar(i) else {
continue
}
let script = unsafeBitCast(
scalar.properties._script,
to: Unicode.Script.self
)
if let parsedScript = scripts[scalar] {
expectEqual(script, parsedScript)
} else {
expectEqual(script, .unknown)
}
}
}
UnicodeScalarPropertiesTest.test("Scalar Script Extensions") {
for i in 0x0 ... 0x10FFFF {
guard let scalar = Unicode.Scalar(i) else {
continue
}
let extensions = scalar.properties._scriptExtensions.map {
unsafeBitCast($0, to: Unicode.Script.self)
}
let script = unsafeBitCast(
scalar.properties._script,
to: Unicode.Script.self
)
if let parsedExtensions = scriptExtensions[scalar] {
expectEqual(extensions, parsedExtensions)
} else {
expectEqual(extensions, [script])
}
}
}
}
runAllTests()
| apache-2.0 | 0d37b270ca03a53f4d4661497a6d9f54 | 35.426966 | 138 | 0.58102 | 4.833996 | false | true | false | false |
instacrate/Subber-api | Sources/App/Middleware/LoggingMiddleware.swift | 2 | 2029 | //
// LoggingMiddleware.swift
// subber-api
//
// Created by Hakon Hanesand on 11/21/16.
//
//
import Foundation
import Vapor
import HTTP
import JSON
extension JSON {
var prettyString: String {
do {
return try String(bytes: serialize(prettyPrint: true))
} catch {
return "Error serializing json into string : \(error)"
}
}
}
extension Model {
var prettyString: String {
do {
return try makeJSON().prettyString
} catch {
return "Error making JSON from model : \(error)"
}
}
}
extension Status {
var isSuccessfulStatus: Bool {
return (statusCode > 199 && statusCode < 400) || statusCode == Status.conflict.statusCode
}
var description: String {
return "\(isSuccessfulStatus ? "Success" : "Failure") - \(statusCode) : \(reasonPhrase)"
}
}
class LoggingMiddleware: Middleware {
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
let response: Response = try next.respond(to: request)
try log(request, response: response)
return response
}
func log(_ request: Request, response: Response) throws {
let failure = { (string: String?) in
if let string = string {
Droplet.logger?.error(string)
}
}
let info = { (string: String?) in
if let string = string {
Droplet.logger?.info(string)
}
}
let logger = response.status.isSuccessfulStatus ? info : failure
logger("")
logger("Request")
logger("URL : \(request.uri)")
logger("Headers : \(request.headers.description)")
if let json = request.json {
try logger("JSON : \(String(bytes: json.serialize(prettyPrint: true)))")
}
logger("Response - \(response.status.description)")
logger("")
}
}
| mit | bb0c343feaf88c698d95ca451624e2a6 | 23.154762 | 97 | 0.552489 | 4.696759 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/00429-vtable.swift | 1 | 1153 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
}
struct S {
static let i: B<Q<T where A"""
}
}
import Foundation
return "\(g, e)
return true
struct d: U -> T) {
}()
extension NSSet {
class B
protocol e == { x }
func g<T) {
}
typealias e : d = b: a {
self)
protocol e = T, b = b: A? = b> T
struct B<Q<T](")
let f : c> (b
let c : AnyObject, AnyObject) {
}
struct d: T.B
class A : A> (self)?
var d = [unowned self.dynamicType)
import Foundation
c> {
let c: a = b: T : NSObject {
func f.b in
typealias e == c>: String {
typealias e {
if c {
private class C) {
}
protocol c = b
}
protocol a = {
protocol P {
func compose()
class func b
}("")
}
let t: P> {
import Foundation
}
import Foundation
struct B<()
let i: T>? = A>()
let c
}
protocol P {
}
}
d.h
import Foundation
S<T -> {
}
}
d.c()
}
enum S<T>Bool
| apache-2.0 | 0b8741a7dd4eaac83a8f2c5527057b6d | 15.471429 | 79 | 0.648742 | 2.868159 | false | false | false | false |
julienbodet/wikipedia-ios | Wikipedia/Code/ArticleCollectionViewController.swift | 1 | 12601 | import UIKit
fileprivate let reuseIdentifier = "ArticleCollectionViewControllerCell"
@objc(WMFArticleCollectionViewControllerDelegate)
protocol ArticleCollectionViewControllerDelegate: NSObjectProtocol {
func articleCollectionViewController(_ articleCollectionViewController: ArticleCollectionViewController, didSelectArticleWithURL: URL)
}
@objc(WMFArticleCollectionViewController)
class ArticleCollectionViewController: ColumnarCollectionViewController, ReadingListHintPresenter, EditableCollection, EventLoggingEventValuesProviding {
@objc var dataStore: MWKDataStore! {
didSet {
readingListHintController = ReadingListHintController(dataStore: dataStore, presenter: self)
}
}
var cellLayoutEstimate: ColumnarCollectionViewLayoutHeightEstimate?
var editController: CollectionViewEditController!
var readingListHintController: ReadingListHintController?
@objc weak var delegate: ArticleCollectionViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
layoutManager.register(ArticleRightAlignedImageCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier, addPlaceholder: true)
setupEditController()
}
open func configure(cell: ArticleRightAlignedImageCollectionViewCell, forItemAt indexPath: IndexPath, layoutOnly: Bool) {
guard let article = article(at: indexPath) else {
return
}
cell.configure(article: article, displayType: .compactList, index: indexPath.item, shouldShowSeparators: true, theme: theme, layoutOnly: layoutOnly)
cell.layoutMargins = layout.itemLayoutMargins
editController.configureSwipeableCell(cell, forItemAt: indexPath, layoutOnly: layoutOnly)
}
open func articleURL(at indexPath: IndexPath) -> URL? {
assert(false, "Subclassers should override this function")
return nil
}
open func imageURL(at indexPath: IndexPath) -> URL? {
guard let article = article(at: indexPath) else {
return nil
}
return article.imageURL(forWidth: traitCollection.wmf_nearbyThumbnailWidth)
}
override func imageURLsForItemAt(_ indexPath: IndexPath) -> Set<URL>? {
guard let imageURL = imageURL(at: indexPath) else {
return nil
}
return [imageURL]
}
open func article(at indexPath: IndexPath) -> WMFArticle? {
assert(false, "Subclassers should override this function")
return nil
}
open func delete(at indexPath: IndexPath) {
assert(false, "Subclassers should override this function")
}
open func canDelete(at indexPath: IndexPath) -> Bool {
return false
}
open func canSave(at indexPath: IndexPath) -> Bool {
guard let articleURL = articleURL(at: indexPath) else {
return false
}
return !dataStore.savedPageList.isSaved(articleURL)
}
open func canUnsave(at indexPath: IndexPath) -> Bool {
guard let articleURL = articleURL(at: indexPath) else {
return false
}
return dataStore.savedPageList.isSaved(articleURL)
}
open func canShare(at indexPath: IndexPath) -> Bool {
return articleURL(at: indexPath) != nil
}
override func contentSizeCategoryDidChange(_ notification: Notification?) {
cellLayoutEstimate = nil
super.contentSizeCategoryDidChange(notification)
}
// MARK: - EventLoggingEventValuesProviding
var eventLoggingCategory: EventLoggingCategory {
assertionFailure("Subclassers should override this property")
return .unknown
}
var eventLoggingLabel: EventLoggingLabel? {
return nil
}
override func collectionView(_ collectionView: UICollectionView, estimatedHeightForItemAt indexPath: IndexPath, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate {
// The layout estimate can be re-used in this case becuause both labels are one line, meaning the cell
// size only varies with font size. The layout estimate is nil'd when the font size changes on trait collection change
if let estimate = cellLayoutEstimate {
return estimate
}
var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 60)
guard let placeholderCell = layoutManager.placeholder(forCellWithReuseIdentifier: reuseIdentifier) as? ArticleRightAlignedImageCollectionViewCell else {
return estimate
}
configure(cell: placeholderCell, forItemAt: indexPath, layoutOnly: true)
// intentionally set all text and unhide image view to get largest possible size
placeholderCell.isImageViewHidden = false
placeholderCell.titleLabel.text = "any"
placeholderCell.descriptionLabel.text = "any"
estimate.height = placeholderCell.sizeThatFits(CGSize(width: columnWidth, height: UIViewNoIntrinsicMetric), apply: false).height
estimate.precalculated = true
cellLayoutEstimate = estimate
return estimate
}
override func metrics(with size: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics {
return ColumnarCollectionViewLayoutMetrics.tableViewMetrics(with: size, readableWidth: readableWidth, layoutMargins: layoutMargins)
}
}
extension ArticleCollectionViewController: AnalyticsContextProviding, AnalyticsViewNameProviding {
var analyticsName: String {
return "ArticleList"
}
var analyticsContext: String {
return analyticsName
}
}
// MARK: - UICollectionViewDataSource
extension ArticleCollectionViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
assert(false, "Subclassers should override this function")
return 0
}
// Override configure(cell: instead to ensure height calculations are accurate
override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
guard let articleCell = cell as? ArticleRightAlignedImageCollectionViewCell else {
return cell
}
configure(cell: articleCell, forItemAt: indexPath, layoutOnly: false)
return cell
}
}
// MARK: - UICollectionViewDelegate
extension ArticleCollectionViewController {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let articleURL = articleURL(at: indexPath) else {
collectionView.deselectItem(at: indexPath, animated: true)
return
}
delegate?.articleCollectionViewController(self, didSelectArticleWithURL: articleURL)
wmf_pushArticle(with: articleURL, dataStore: dataStore, theme: theme, animated: true)
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
editController.deconfigureSwipeableCell(cell, forItemAt: indexPath)
}
}
// MARK: - UIViewControllerPreviewingDelegate
extension ArticleCollectionViewController {
override func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard !editController.isActive else {
return nil // don't allow 3d touch when swipe actions are active
}
guard let indexPath = collectionView.indexPathForItem(at: location),
let cell = collectionView.cellForItem(at: indexPath) as? ArticleRightAlignedImageCollectionViewCell,
let url = articleURL(at: indexPath)
else {
return nil
}
previewingContext.sourceRect = cell.convert(cell.bounds, to: collectionView)
let articleViewController = WMFArticleViewController(articleURL: url, dataStore: dataStore, theme: self.theme)
articleViewController.articlePreviewingActionsDelegate = self
articleViewController.wmf_addPeekableChildViewController(for: url, dataStore: dataStore, theme: theme)
return articleViewController
}
override func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
viewControllerToCommit.wmf_removePeekableChildViewControllers()
wmf_push(viewControllerToCommit, animated: true)
}
}
extension ArticleCollectionViewController: ActionDelegate {
func didPerformBatchEditToolbarAction(_ action: BatchEditToolbarAction) -> Bool {
assert(false, "Subclassers should override this function")
return false
}
func willPerformAction(_ action: Action) -> Bool {
guard let article = article(at: action.indexPath) else {
return false
}
guard action.type == .unsave else {
return self.editController.didPerformAction(action)
}
let alertController = ReadingListsAlertController()
let cancel = ReadingListsAlertActionType.cancel.action { self.editController.close() }
let delete = ReadingListsAlertActionType.unsave.action { let _ = self.editController.didPerformAction(action) }
return alertController.showAlert(presenter: self, for: [article], with: [cancel, delete], completion: nil) {
return self.editController.didPerformAction(action)
}
}
func didPerformAction(_ action: Action) -> Bool {
let indexPath = action.indexPath
let sourceView = collectionView.cellForItem(at: indexPath)
switch action.type {
case .delete:
delete(at: indexPath)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, CommonStrings.articleDeletedNotification(articleCount: 1))
return true
case .save:
if let articleURL = articleURL(at: indexPath) {
dataStore.savedPageList.addSavedPage(with: articleURL)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, CommonStrings.accessibilitySavedNotification)
if let article = article(at: indexPath) {
readingListHintController?.didSave(true, article: article, theme: theme)
ReadingListsFunnel.shared.logSave(category: eventLoggingCategory, label: eventLoggingLabel, articleURL: articleURL)
}
return true
}
case .unsave:
if let articleURL = articleURL(at: indexPath) {
dataStore.savedPageList.removeEntry(with: articleURL)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, CommonStrings.accessibilityUnsavedNotification)
if let article = article(at: indexPath) {
readingListHintController?.didSave(false, article: article, theme: theme)
ReadingListsFunnel.shared.logUnsave(category: eventLoggingCategory, label: eventLoggingLabel, articleURL: articleURL)
}
return true
}
case .share:
return share(article: article(at: indexPath), articleURL: articleURL(at: indexPath), at: indexPath, dataStore: dataStore, theme: theme, eventLoggingCategory: eventLoggingCategory, eventLoggingLabel: eventLoggingLabel, sourceView: sourceView)
}
return false
}
func availableActions(at indexPath: IndexPath) -> [Action] {
var actions: [Action] = []
if canSave(at: indexPath) {
actions.append(ActionType.save.action(with: self, indexPath: indexPath))
} else if canUnsave(at: indexPath) {
actions.append(ActionType.unsave.action(with: self, indexPath: indexPath))
}
if canShare(at: indexPath) {
actions.append(ActionType.share.action(with: self, indexPath: indexPath))
}
if canDelete(at: indexPath) {
actions.append(ActionType.delete.action(with: self, indexPath: indexPath))
}
return actions
}
}
extension ArticleCollectionViewController: ShareableArticlesProvider {}
| mit | fb61ee129817a9df29421a996aff593f | 43.843416 | 253 | 0.70169 | 5.806912 | false | false | false | false |
tmandry/Swindler | Sources/Space.swift | 1 | 6911 | import Cocoa
class OSXSpaceObserver: NSObject, NSWindowDelegate {
private var trackers: [Int: SpaceTracker] = [:]
private weak var ssd: SystemScreenDelegate?
private var sst: SystemSpaceTracker
private weak var notifier: EventNotifier?
init(_ notifier: EventNotifier?, _ ssd: SystemScreenDelegate, _ sst: SystemSpaceTracker) {
self.notifier = notifier
self.ssd = ssd
self.sst = sst
super.init()
for screen in ssd.screens {
makeWindow(screen)
}
sst.onSpaceChanged { [weak self] in
self?.emitSpaceWillChangeEvent()
}
// TODO: Detect screen configuration changes
}
/// Create an invisible window for tracking the current space.
///
/// This helps us identify the space when we return to it in the future.
/// It also helps us detect when a space is closed and merged into another.
/// Without the window events we wouldn't have a way of noticing when this
/// happened.
@discardableResult
private func makeWindow(_ screen: ScreenDelegate) -> Int {
let win = sst.makeTracker(screen)
trackers[win.id] = win
return win.id
}
/// Emits a SpaceWillChangeEvent on the notifier this observer was
/// constructed with.
///
/// Used during initialization.
func emitSpaceWillChangeEvent() {
guard let ssd = ssd else { return }
let visible = sst.visibleIds()
log.debug("spaceChanged: visible=\(visible)")
let screens = ssd.screens
var visibleByScreen = [[Int]](repeating: [], count: screens.count)
for id in visible {
// This is O(N^2) in the number of screens, but thankfully that
// never gets large.
// TODO: Use directDisplayID?
guard let screen = trackers[id]?.screen(ssd) else {
log.info("Window id \(id) not associated with any screen")
continue
}
for (idx, scr) in screens.enumerated() {
if scr.equalTo(screen) {
visibleByScreen[idx].append(id)
break
}
}
}
var visiblePerScreen: [Int] = []
for (idx, visible) in visibleByScreen.enumerated() {
if let id = visible.min() {
visiblePerScreen.append(id)
} else {
visiblePerScreen.append(makeWindow(screens[idx]))
}
}
notifier?.notify(SpaceWillChangeEvent(external: true, ids: visiblePerScreen))
}
}
protocol SystemSpaceTracker {
/// Installs a handler to be called when the current space changes.
func onSpaceChanged(_ handler: @escaping () -> ())
/// Creates a tracker for the current space on the given screen.
func makeTracker(_ screen: ScreenDelegate) -> SpaceTracker
/// Returns the list of IDs of SpaceTrackers whose spaces are currently visible.
func visibleIds() -> [Int]
}
class OSXSystemSpaceTracker: SystemSpaceTracker {
func onSpaceChanged(_ handler: @escaping () -> ()) {
let sharedWorkspace = NSWorkspace.shared
let notificationCenter = sharedWorkspace.notificationCenter
notificationCenter.addObserver(
forName: NSWorkspace.activeSpaceDidChangeNotification,
object: sharedWorkspace,
queue: nil
) { _ in handler() }
}
func makeTracker(_ screen: ScreenDelegate) -> SpaceTracker {
OSXSpaceTracker(screen)
}
func visibleIds() -> [Int] {
(NSWindow.windowNumbers(options: []) ?? []) as! [Int]
}
}
protocol SpaceTracker {
var id: Int { get }
func screen(_ ssd: SystemScreenDelegate) -> ScreenDelegate?
}
class OSXSpaceTracker: NSObject, NSWindowDelegate, SpaceTracker {
let win: NSWindow
var id: Int { win.windowNumber }
init(_ screen: ScreenDelegate) {
//win = NSWindow(contentViewController: NSViewController(nibName: nil, bundle: nil))
// Size must be non-zero to receive occlusion state events.
let rect = /*NSRect.zero */NSRect(x: 0, y: 0, width: 1, height: 1)
win = NSWindow(
contentRect: rect,
styleMask: .borderless/*[.titled, .resizable, .miniaturizable]*/,
backing: .buffered,
defer: true,
screen: screen.native)
win.isReleasedWhenClosed = false
win.ignoresMouseEvents = true
win.hasShadow = false
win.animationBehavior = .none
win.backgroundColor = NSColor.clear
win.level = .floating
win.collectionBehavior = [.transient, .ignoresCycle, .fullScreenAuxiliary]
if #available(macOS 10.11, *) {
win.collectionBehavior.update(with: .fullScreenDisallowsTiling)
}
super.init()
win.delegate = self
win.makeKeyAndOrderFront(nil)
log.debug("new window windowNumber=\(win.windowNumber)")
}
func screen(_ ssd: SystemScreenDelegate) -> ScreenDelegate? {
guard let screen = win.screen else {
return nil
}
// This class should only be used with a "real" SystemScreenDelegate impl.
return ssd.delegateForNative(screen: screen)!
}
func windowDidChangeScreen(_ notification: Notification) {
let win = notification.object as! NSWindow
log.debug("window \(win.windowNumber) changed screen; active=\(win.isOnActiveSpace)")
}
func windowDidChangeOcclusionState(_ notification: Notification) {
let win = notification.object as! NSWindow
log.debug("""
window \(win.windowNumber) occstchanged; \
occVis=\(win.occlusionState.contains(NSWindow.OcclusionState.visible)), \
vis=\(win.isVisible), activeSpace=\(win.isOnActiveSpace)
""")
let visible = (NSWindow.windowNumbers(options: []) ?? []) as! [Int]
log.debug("visible=\(visible)")
// TODO: Use this event to detect space merges.
}
}
class FakeSystemSpaceTracker: SystemSpaceTracker {
init() {}
var spaceChangeHandler: Optional<() -> ()> = nil
func onSpaceChanged(_ handler: @escaping () -> ()) {
spaceChangeHandler = handler
}
var trackersMade: [StubSpaceTracker] = []
func makeTracker(_ screen: ScreenDelegate) -> SpaceTracker {
let tracker = StubSpaceTracker(screen, id: nextSpaceId)
trackersMade.append(tracker)
visible.append(tracker.id)
return tracker
}
var nextSpaceId: Int { trackersMade.count + 1 }
var visible: [Int] = []
func visibleIds() -> [Int] { visible }
}
class StubSpaceTracker: SpaceTracker {
var screen: ScreenDelegate?
var id: Int
init(_ screen: ScreenDelegate?, id: Int) {
self.screen = screen
self.id = id
}
func screen(_ ssd: SystemScreenDelegate) -> ScreenDelegate? { screen }
}
| mit | 989c4fd03abac87d8a2f95890512e952 | 33.383085 | 94 | 0.61829 | 4.546711 | false | false | false | false |
mattorb/iOS-Swift-Key-Smash | KeySmash/ViewController.swift | 1 | 1617 | import UIKit
import Foundation
import AVFoundation
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var textField: UITextField!
let modeList: [Mode] = [SayPressedKey(), HuntForKey(), OrderedAlphabet(), Counting()]
var currentModeIndex = 0
var currentMode : Mode { return modeList[currentModeIndex] }
let keyCommandCache = externalKeyboardKeys(callback: #selector(sayKey))
override func viewDidLoad() {
super.viewDidLoad()
textField.becomeFirstResponder() // focus on textField brings up the keyboard
textField.delegate=self
currentMode.start()
}
override var keyCommands: [UIKeyCommand]? {
get {
return keyCommandCache
}
}
@objc func sayKey(command:UIKeyCommand) {
if(command.input == UIKeyCommand.inputRightArrow)
{
nextMode()
}
else
{
let input = command.input ?? ""
currentMode.respondTo(key: input)
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool // return NO to not change text
{
return false; // don't actually change the textfield
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
currentMode.respondTo(key: "enter")
return false //ignore enter
}
func nextMode()
{
currentModeIndex+=1
if(currentModeIndex > modeList.count-1) { currentModeIndex=0; }
currentMode.start()
}
}
| mit | 842454fa82435d38c427a5a81980c3bf | 26.40678 | 159 | 0.624613 | 5.117089 | false | false | false | false |
aschwaighofer/swift | test/IRGen/big_types_corner_cases.swift | 2 | 17532 | // XFAIL: CPU=powerpc64le
// XFAIL: CPU=s390x
// RUN: %target-swift-frontend -disable-type-layout -enable-large-loadable-types %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
// REQUIRES: optimized_stdlib
// UNSUPPORTED: CPU=powerpc64le
public struct BigStruct {
var i0 : Int32 = 0
var i1 : Int32 = 1
var i2 : Int32 = 2
var i3 : Int32 = 3
var i4 : Int32 = 4
var i5 : Int32 = 5
var i6 : Int32 = 6
var i7 : Int32 = 7
var i8 : Int32 = 8
}
func takeClosure(execute block: () -> Void) {
}
class OptionalInoutFuncType {
private var lp : BigStruct?
private var _handler : ((BigStruct?, Error?) -> ())?
func execute(_ error: Error?) {
var p : BigStruct?
var handler: ((BigStruct?, Error?) -> ())?
takeClosure {
p = self.lp
handler = self._handler
self._handler = nil
}
handler?(p, error)
}
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} i32 @main(i32 %0, i8** %1)
// CHECK: call void @llvm.lifetime.start
// CHECK: call void @llvm.memcpy
// CHECK: call void @llvm.lifetime.end
// CHECK: ret i32 0
let bigStructGlobalArray : [BigStruct] = [
BigStruct()
]
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} internal swiftcc void @"$s22big_types_corner_cases21OptionalInoutFuncTypeC7executeyys5Error_pSgFyyXEfU_"(%T22big_types_corner_cases9BigStructVSg* nocapture dereferenceable({{.*}}) %0, %T22big_types_corner_cases21OptionalInoutFuncTypeC* %1, %T22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_Sg* nocapture dereferenceable({{.*}})
// CHECK: call void @"$s22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_SgWOe
// CHECK: call void @"$s22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_SgWOy
// CHECK: ret void
public func f1_returns_BigType(_ x: BigStruct) -> BigStruct {
return x
}
public func f2_returns_f1() -> (_ x: BigStruct) -> BigStruct {
return f1_returns_BigType
}
public func f3_uses_f2() {
let x = BigStruct()
let useOfF2 = f2_returns_f1()
let _ = useOfF2(x)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases10f3_uses_f2yyF"()
// CHECK: call swiftcc void @"$s22big_types_corner_cases9BigStructVACycfC"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret
// CHECK: call swiftcc { i8*, %swift.refcounted* } @"$s22big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF"()
// CHECK: call swiftcc void {{.*}}(%T22big_types_corner_cases9BigStructV* noalias nocapture sret {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself {{.*}})
// CHECK: ret void
public func f4_tuple_use_of_f2() {
let x = BigStruct()
let tupleWithFunc = (f2_returns_f1(), x)
let useOfF2 = tupleWithFunc.0
let _ = useOfF2(x)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases18f4_tuple_use_of_f2yyF"()
// CHECK: [[TUPLE:%.*]] = call swiftcc { i8*, %swift.refcounted* } @"$s22big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF"()
// CHECK: [[TUPLE_EXTRACT:%.*]] = extractvalue { i8*, %swift.refcounted* } [[TUPLE]], 0
// CHECK: [[CAST_EXTRACT:%.*]] = bitcast i8* [[TUPLE_EXTRACT]] to void (%T22big_types_corner_cases9BigStructV*, %T22big_types_corner_cases9BigStructV*, %swift.refcounted*)*
// CHECK: call swiftcc void [[CAST_EXTRACT]](%T22big_types_corner_cases9BigStructV* noalias nocapture sret {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself %{{.*}})
// CHECK: ret void
public class BigClass {
public init() {
}
public var optVar: ((BigStruct)-> Void)? = nil
func useBigStruct(bigStruct: BigStruct) {
optVar!(bigStruct)
}
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases8BigClassC03useE6Struct0aH0yAA0eH0V_tF"(%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) %0, %T22big_types_corner_cases8BigClassC* swiftself %1)
// CHECK: [[BITCAST:%.*]] = bitcast i8* {{.*}} to void (%T22big_types_corner_cases9BigStructV*, %swift.refcounted*)*
// CHECK: call swiftcc void [[BITCAST]](%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) %0, %swift.refcounted* swiftself
// CHECK: ret void
public struct MyStruct {
public let a: Int
public let b: String?
}
typealias UploadFunction = ((MyStruct, Int?) -> Void) -> Void
func takesUploader(_ u: UploadFunction) { }
class Foo {
func blam() {
takesUploader(self.myMethod) // crash compiling this
}
func myMethod(_ callback: (MyStruct, Int) -> Void) -> Void { }
}
// CHECK-LABEL: define internal swiftcc void @"$s22big_types_corner_cases3FooC4blamyyFyyAA8MyStructV_SitXEcACcfu_yyAF_SitXEcfu0_"(i8* %0, %swift.opaque* %1, %T22big_types_corner_cases3FooC* %2)
public enum LargeEnum {
public enum InnerEnum {
case simple(Int64)
case hard(Int64, String?, Int64)
}
case Empty1
case Empty2
case Full(InnerEnum)
}
public func enumCallee(_ x: LargeEnum) {
switch x {
case .Full(let inner): print(inner)
case .Empty1: break
case .Empty2: break
}
}
// CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases10enumCalleeyAA9LargeEnumOF"(%T22big_types_corner_cases9LargeEnumO* noalias nocapture dereferenceable({{.*}}) %0) #0 {
// CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO05InnerF0O
// CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO
// CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64
// CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64
// CHECK-64: $ss5print_9separator10terminatoryypd_S2StF
// CHECK-64: ret void
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} internal swiftcc void @"$s22big_types_corner_cases8SuperSubC1fyyFAA9BigStructVycfU_"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret %0, %T22big_types_corner_cases8SuperSubC* %1)
// CHECK-64: [[ALLOC1:%.*]] = alloca %T22big_types_corner_cases9BigStructV
// CHECK-64: [[ALLOC2:%.*]] = alloca %T22big_types_corner_cases9BigStructV
// CHECK-64: [[ALLOC3:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg
// CHECK-64: call swiftcc void @"$s22big_types_corner_cases9SuperBaseC4boomAA9BigStructVyF"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret [[ALLOC1]], %T22big_types_corner_cases9SuperBaseC* swiftself {{.*}})
// CHECK: ret void
class SuperBase {
func boom() -> BigStruct {
return BigStruct()
}
}
class SuperSub : SuperBase {
override func boom() -> BigStruct {
return BigStruct()
}
func f() {
let _ = {
nil ?? super.boom()
}
}
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases10MUseStructV16superclassMirrorAA03BigF0VSgvg"(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret %0, %T22big_types_corner_cases10MUseStructV* noalias nocapture swiftself dereferenceable({{.*}}) %1)
// CHECK: [[ALLOC:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg
// CHECK: [[LOAD:%.*]] = load %swift.refcounted*, %swift.refcounted** %.callInternalLet.data
// CHECK: call swiftcc void %7(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret [[ALLOC]], %swift.refcounted* swiftself [[LOAD]])
// CHECK: ret void
public struct MUseStruct {
var x = BigStruct()
public var superclassMirror: BigStruct? {
return callInternalLet()
}
internal let callInternalLet: () -> BigStruct?
}
// CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases18stringAndSubstringSS_s0G0VtyF"(<{ %TSS, %Ts9SubstringV }>* noalias nocapture sret %0) #0 {
// CHECK-LABEL-32: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases18stringAndSubstringSS_s0G0VtyF"(<{ %TSS, [4 x i8], %Ts9SubstringV }>* noalias nocapture sret %0) #0 {
// CHECK: alloca %TSs
// CHECK: alloca %TSs
// CHECK: ret void
public func stringAndSubstring() -> (String, Substring) {
let s = "Hello, World"
let a = Substring(s).dropFirst()
return (s, a)
}
func bigStructGet() -> BigStruct {
return BigStruct()
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases11testGetFuncyyF"()
// CHECK: ret void
public func testGetFunc() {
let testGetPtr: @convention(thin) () -> BigStruct = bigStructGet
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases7TestBigC4testyyF"(%T22big_types_corner_cases7TestBigC* swiftself %0)
// CHECK: [[CALL1:%.*]] = call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$sSayy22big_types_corner_cases9BigStructVcSgGMD"
// CHECK: [[CALL2:%.*]] = call i8** @"$sSayy22big_types_corner_cases9BigStructVcSgGSayxGSlsWl
// CHECK: call swiftcc void @"$sSlsE10firstIndex5where0B0QzSgSb7ElementQzKXE_tKF"(%TSq.{{.*}}* noalias nocapture sret %{{[0-9]+}}, i8* bitcast ({{.*}}* @"$s22big_types_corner_cases9BigStruct{{.*}}_TRTA{{(\.ptrauth)?}}" to i8*), %swift.opaque* %{{[0-9]+}}, %swift.type* %{{[0-9]+}}, i8** [[CALL2]]
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases7TestBigC5test2yyF"(%T22big_types_corner_cases7TestBigC* swiftself %0)
// CHECK: [[CALL1:%.*]] = call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$sSaySS2ID_y22big_types_corner_cases9BigStructVcSg7handlertGMD"
// CHECK: [[CALL2:%.*]] = call i8** @"$sSaySS2ID_y22big_types_corner_cases9BigStructVcSg7handlertGSayxGSlsWl"
// CHECK: call swiftcc void @"$sSlss16IndexingIteratorVyxG0B0RtzrlE04makeB0ACyF"(%Ts16IndexingIteratorV{{.*}}* noalias nocapture sret {{.*}}, %swift.type* [[CALL1]], i8** [[CALL2]], %swift.opaque* noalias nocapture swiftself {{.*}})
// CHECK: ret void
class TestBig {
typealias Handler = (BigStruct) -> Void
func test() {
let arr = [Handler?]()
let d = arr.firstIndex(where: { _ in true })
}
func test2() {
let arr: [(ID: String, handler: Handler?)] = []
for (_, handler) in arr {
takeClosure {
handler?(BigStruct())
}
}
}
}
struct BigStructWithFunc {
var incSize : BigStruct
var foo: ((BigStruct) -> Void)?
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases20UseBigStructWithFuncC5crashyyF"(%T22big_types_corner_cases20UseBigStructWithFuncC* swiftself %0)
// CHECK: call swiftcc void @"$s22big_types_corner_cases20UseBigStructWithFuncC10callMethod
// CHECK: ret void
class UseBigStructWithFunc {
var optBigStructWithFunc: BigStructWithFunc?
func crash() {
guard let bigStr = optBigStructWithFunc else { return }
callMethod(ptr: bigStr.foo)
}
private func callMethod(ptr: ((BigStruct) -> Void)?) -> () {
}
}
struct BiggerString {
var str: String
var double: Double
}
struct LoadableStructWithBiggerString {
public var a1: BiggerString
public var a2: [String]
public var a3: [String]
}
class ClassWithLoadableStructWithBiggerString {
public func f() -> LoadableStructWithBiggerString {
return LoadableStructWithBiggerString(a1: BiggerString(str:"", double:0.0), a2: [], a3: [])
}
}
//===----------------------------------------------------------------------===//
// SR-8076
//===----------------------------------------------------------------------===//
public typealias sr8076_Filter = (BigStruct) -> Bool
public protocol sr8076_Query {
associatedtype Returned
}
public protocol sr8076_ProtoQueryHandler {
func forceHandle_1<Q: sr8076_Query>(query: Q) -> Void
func forceHandle_2<Q: sr8076_Query>(query: Q) -> (Q.Returned, BigStruct?)
func forceHandle_3<Q: sr8076_Query>(query: Q) -> (Q.Returned, sr8076_Filter?)
func forceHandle_4<Q: sr8076_Query>(query: Q) throws -> (Q.Returned, sr8076_Filter?)
}
public protocol sr8076_QueryHandler: sr8076_ProtoQueryHandler {
associatedtype Handled: sr8076_Query
func handle_1(query: Handled) -> Void
func handle_2(query: Handled) -> (Handled.Returned, BigStruct?)
func handle_3(query: Handled) -> (Handled.Returned, sr8076_Filter?)
func handle_4(query: Handled) throws -> (Handled.Returned, sr8076_Filter?)
}
public extension sr8076_QueryHandler {
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_15queryyqd___tAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself %1)
// CHECK: call swiftcc void {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}})
// CHECK: ret void
func forceHandle_1<Q: sr8076_Query>(query: Q) -> Void {
guard let body = handle_1 as? (Q) -> Void else {
fatalError("handler \(self) is expected to handle query \(query)")
}
body(query)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_25query8ReturnedQyd___AA9BigStructVSgtqd___tAA0e1_F0Rd__lF"(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret %0, %swift.opaque* noalias nocapture %1, %swift.opaque* noalias nocapture %2, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself %3)
// CHECK: [[ALLOC:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg
// CHECK: call swiftcc void {{.*}}(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret [[ALLOC]], %swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}})
// CHECK: ret void
func forceHandle_2<Q: sr8076_Query>(query: Q) -> (Q.Returned, BigStruct?) {
guard let body = handle_2 as? (Q) -> (Q.Returned, BigStruct?) else {
fatalError("handler \(self) is expected to handle query \(query)")
}
return body(query)
}
// CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc { i64, i64 } @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_35query8ReturnedQyd___SbAA9BigStructVcSgtqd___tAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.opaque* noalias nocapture %1, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself %2)
// CHECK-64: {{.*}} = call swiftcc { i64, i64 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}})
// CHECK-64: ret { i64, i64 }
// CHECK-LABEL-32: define{{( dllexport)?}}{{( protected)?}} swiftcc { i32, i32} @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_35query8ReturnedQyd___SbAA9BigStructVcSgtqd___tAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.opaque* noalias nocapture %1, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself %2)
// CHECK-32: {{.*}} = call swiftcc { i32, i32 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}})
// CHECK-32: ret { i32, i32 }
func forceHandle_3<Q: sr8076_Query>(query: Q) -> (Q.Returned, sr8076_Filter?) {
guard let body = handle_3 as? (Q) -> (Q.Returned, sr8076_Filter?) else {
fatalError("handler \(self) is expected to handle query \(query)")
}
return body(query)
}
// CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc { i64, i64 } @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_45query8ReturnedQyd___SbAA9BigStructVcSgtqd___tKAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.opaque* noalias nocapture %1, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself %2, %swift.error** swifterror %3)
// CHECK-64: {{.*}} = call swiftcc { i64, i64 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}, %swift.error** noalias nocapture swifterror {{.*}})
// CHECK-64: ret { i64, i64 }
// CHECK-LABEL-32: define{{( dllexport)?}}{{( protected)?}} swiftcc { i32, i32} @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_45query8ReturnedQyd___SbAA9BigStructVcSgtqd___tKAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.opaque* noalias nocapture %1, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself %2, %swift.error** swifterror %3)
// CHECK-32: {{.*}} = call swiftcc { i32, i32 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}, %swift.error** noalias nocapture {{.*}})
// CHECK-32: ret { i32, i32 }
func forceHandle_4<Q: sr8076_Query>(query: Q) throws -> (Q.Returned, sr8076_Filter?) {
guard let body = handle_4 as? (Q) throws -> (Q.Returned, sr8076_Filter?) else {
fatalError("handler \(self) is expected to handle query \(query)")
}
return try body(query)
}
}
public func foo() -> Optional<(a: Int?, b: Bool, c: (Int?)->BigStruct?)> {
return nil
}
public func dontAssert() {
let _ = foo()
}
| apache-2.0 | 8b7049797589be4e66a09817a502f49c | 48.665722 | 484 | 0.673682 | 3.445078 | false | false | false | false |
efremidze/Cluster | Example/AnnotationView.swift | 1 | 1307 | //
// AnnotationView.swift
// Example
//
// Created by Lasha Efremidze on 10/9/18.
// Copyright © 2018 efremidze. All rights reserved.
//
import UIKit
import MapKit
import Cluster
class CountClusterAnnotationView: ClusterAnnotationView {
override func configure() {
super.configure()
guard let annotation = annotation as? ClusterAnnotation else { return }
let count = annotation.annotations.count
let diameter = radius(for: count) * 2
self.frame.size = CGSize(width: diameter, height: diameter)
self.layer.cornerRadius = self.frame.width / 2
self.layer.masksToBounds = true
self.layer.borderColor = UIColor.white.cgColor
self.layer.borderWidth = 1.5
}
func radius(for count: Int) -> CGFloat {
if count < 5 {
return 12
} else if count < 10 {
return 16
} else {
return 20
}
}
}
class ImageCountClusterAnnotationView: ClusterAnnotationView {
lazy var once: Void = { [unowned self] in
self.countLabel.frame.size.width -= 6
self.countLabel.frame.origin.x += 3
self.countLabel.frame.origin.y -= 6
}()
override func layoutSubviews() {
super.layoutSubviews()
_ = once
}
}
| mit | 7c108e24facc671e4a023b1fce59e353 | 25.653061 | 79 | 0.611026 | 4.33887 | false | false | false | false |
szehnder/Swell | Swell/Formatter.swift | 1 | 6696 | //
// Formatter.swift
// Swell
//
// Created by Hubert Rabago on 6/20/14.
// Copyright (c) 2014 Minute Apps LLC. All rights reserved.
//
/// A Log Formatter implementation generates the string that will be sent to a log location
/// if the log level requirement is met by a call to log a message.
public protocol LogFormatter {
/// Formats the message provided for the given logger
func formatLog<T>(logger: Logger, level: LogLevel, @autoclosure message: () -> T,
filename: String?, line: Int?, function: String?) -> String;
/// Returns an instance of this class given a configuration string
static func logFormatterForString(formatString: String) -> LogFormatter;
/// Returns a string useful for describing this class and how it is configured
func description() -> String;
}
public enum QuickFormatterFormat: Int {
case MessageOnly = 0x0001
case LevelMessage = 0x0101
case NameMessage = 0x0011
case LevelNameMessage = 0x0111
case DateLevelMessage = 0x1101
case DateMessage = 0x1001
case All = 0x1111
}
/// QuickFormatter provides some limited options for formatting log messages.
/// Its primary advantage over FlexFormatter is speed - being anywhere from 20% to 50% faster
/// because of its limited options.
public class QuickFormatter: LogFormatter {
let format: QuickFormatterFormat
public init(format: QuickFormatterFormat = .LevelNameMessage) {
self.format = format
}
public func formatLog<T>(logger: Logger, level: LogLevel, @autoclosure message givenMessage: () -> T,
filename: String?, line: Int?, function: String?) -> String {
var s: String;
let message = givenMessage()
switch format {
case .LevelNameMessage:
s = "\(level.label) \(logger.name): \(message)";
case .DateLevelMessage:
s = "\(NSDate()) \(level.label): \(message)";
case .MessageOnly:
s = "\(message)";
case .NameMessage:
s = "\(logger.name): \(message)";
case .LevelMessage:
s = "\(level.label): \(message)";
case .DateMessage:
s = "\(NSDate()) \(message)";
case .All:
s = "\(NSDate()) \(level.label) \(logger.name): \(message)";
}
return s
}
public class func logFormatterForString(formatString: String) -> LogFormatter {
var format: QuickFormatterFormat
switch formatString {
case "LevelNameMessage": format = .LevelNameMessage
case "DateLevelMessage": format = .DateLevelMessage
case "MessageOnly": format = .MessageOnly
case "LevelMessage": format = .LevelMessage
case "NameMessage": format = .NameMessage
case "DateMessage": format = .DateMessage
default: format = .All
}
return QuickFormatter(format: format)
}
public func description() -> String {
var s: String;
switch format {
case .LevelNameMessage:
s = "LevelNameMessage";
case .DateLevelMessage:
s = "DateLevelMessage";
case .MessageOnly:
s = "MessageOnly";
case .LevelMessage:
s = "LevelMessage";
case .NameMessage:
s = "NameMessage";
case .DateMessage:
s = "DateMessage";
case .All:
s = "All";
}
return "QuickFormatter format=\(s)"
}
}
public enum FlexFormatterPart: Int {
case DATE
case NAME
case LEVEL
case MESSAGE
case LINE
case FUNC
}
/// FlexFormatter provides more control over the log format, allowing
/// the flexibility to specify what data appears and on what order.
public class FlexFormatter: LogFormatter {
var format: [FlexFormatterPart]
public init(parts: FlexFormatterPart...) {
format = parts
// Same thing as below
//format = [FlexFormatterPart]()
//for part in parts {
// format += part
//}
}
/// This overload is needed (as of Beta 3) because
/// passing an array to a variadic param is not yet supported
init(parts: [FlexFormatterPart]) {
format = parts
}
public func formatLog<T>(logger: Logger, level: LogLevel, @autoclosure message givenMessage: () -> T,
filename: String?, line: Int?, function: String?) -> String {
var logMessage = ""
for (index, part) in format.enumerate() {
switch part {
case .MESSAGE:
let message = givenMessage()
logMessage += "\(message)"
case .NAME: logMessage += logger.name
case .LEVEL: logMessage += level.label
case .DATE: logMessage += NSDate().description
case .LINE:
if (filename != nil) && (line != nil) {
logMessage += "[\((filename! as NSString).lastPathComponent):\(line!)]"
}
case .FUNC:
if (function != nil) {
logMessage += "[\(function)()]"
}
}
if (index < format.count-1) {
if (format[index+1] == .MESSAGE) {
logMessage += ":"
}
logMessage += " "
}
}
return logMessage
}
public class func logFormatterForString(formatString: String) -> LogFormatter {
var formatSpec = [FlexFormatterPart]()
let parts = formatString.uppercaseString.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
for part in parts {
switch part {
case "MESSAGE": formatSpec += [.MESSAGE]
case "NAME": formatSpec += [.NAME]
case "LEVEL": formatSpec += [.LEVEL]
case "LINE": formatSpec += [.LINE]
case "FUNC": formatSpec += [.FUNC]
default: formatSpec += [.DATE]
}
}
return FlexFormatter(parts: formatSpec)
}
public func description() -> String {
var desc = ""
for (index, part) in format.enumerate() {
switch part {
case .MESSAGE: desc += "MESSAGE"
case .NAME: desc += "NAME"
case .LEVEL: desc += "LEVEL"
case .DATE: desc += "DATE"
case .LINE: desc += "LINE"
case .FUNC: desc += "FUNC"
}
if (index < format.count-1) {
desc += " "
}
}
return "FlexFormatter with \(desc)"
}
}
| apache-2.0 | 9adde0c8b8de3a7be25dd4bccf3e5c65 | 31.192308 | 126 | 0.557049 | 4.782857 | false | false | false | false |
mathewa6/Practise | LC/LongestSubstringWithoutRepeatingCharacters.playground/Contents.swift | 1 | 810 |
//Insert each character into a set and then check for new characters existing in the set.
// TODO: - Try http://www.geeksforgeeks.org/length-of-the-longest-substring-without-repeating-characters/ for alt solution.
class Solution {
func lengthOfLongestSubstring(s: String) -> Int {
var bowl = [Character : Int]()
var count = 0, left = 0
for (i, char) in s.characters.enumerate() {
if let key = bowl[char] {
count = max(count, i - left)
left = max(left, key + 1)
}
bowl[char] = i
}
return max(count, s.characters.count - left)
}
}
let sol = Solution()
let input = "dvdf" //jxgqtuorkyqyvnpmutwxhqufgazxfzbqzigseulrubpqree
sol.lengthOfLongestSubstring(input)
| mit | f0153f4844d67dce8b5219564ffe32f6 | 30.153846 | 123 | 0.591358 | 3.648649 | false | false | false | false |
diwu/LeetCode-Solutions-in-Swift | Solutions/Solutions/Easy/Easy_007_Reverse_Integer.swift | 1 | 2030 | /*
https://oj.leetcode.com/problems/reverse-integer/
#7 Reverse Integer
Level: easy
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
Inspired by @wshaoxuan at https://leetcode.com/discuss/120/how-do-we-handle-the-overflow-case
*/
//Int.max 9,223,372,036,854,775,807
//Int.min -9,223,372,036,854,775,808
struct Easy_007_Reverse_Integer {
// t = O(N), s = O(1)
static func reverse(_ x: Int) -> Int {
var negtive: Bool
var i: UInt
if x < 0 {
negtive = true
if x == Int.min {
// The "minus 1 then add 1" trick is used to negate Int.min without overflow
i = UInt(-(x+1))
i += 1
} else {
i = UInt(-x)
}
} else {
negtive = false
i = UInt(x)
}
var res:UInt = 0
while i > 0 {
res = res * 10 + i % 10
i = i / 10
}
if negtive == false && res > UInt(Int.max) {
return 0
} else if negtive == true && res == UInt(Int.max) + 1 {
// When input is the reverse of Int.min
return (-1) * Int(res-1) - 1
} else if negtive == true && res > UInt(Int.max) + 1 {
return 0
}
if negtive {
return (-1) * Int(res)
} else {
return Int(res)
}
}
}
| mit | 1b5f6b26d00eea2207483bde48bac42d | 26.808219 | 170 | 0.560591 | 3.605684 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/Discovery/Controller/DiscoveryViewController.swift | 1 | 6628 | import KsApi
import Library
import Prelude
import UIKit
internal final class DiscoveryViewController: UIViewController {
fileprivate let viewModel: DiscoveryViewModelType = DiscoveryViewModel()
fileprivate var dataSource: DiscoveryPagesDataSource?
private var recommendationsChangedObserver: Any?
private weak var navigationHeaderViewController: DiscoveryNavigationHeaderViewController!
private var optimizelyConfiguredObserver: Any?
private var optimizelyConfigurationFailedObserver: Any?
private weak var pageViewController: UIPageViewController!
private weak var sortPagerViewController: SortPagerViewController!
internal static func instantiate() -> DiscoveryViewController {
return Storyboard.Discovery.instantiate(DiscoveryViewController.self)
}
override func viewDidLoad() {
super.viewDidLoad()
self.pageViewController = self.children
.compactMap { $0 as? UIPageViewController }.first
self.pageViewController.ksr_setViewControllers(
[.init()],
direction: .forward,
animated: false,
completion: nil
)
self.pageViewController.delegate = self
self.sortPagerViewController = self.children
.compactMap { $0 as? SortPagerViewController }.first
self.sortPagerViewController.delegate = self
self.navigationHeaderViewController = self.children
.compactMap { $0 as? DiscoveryNavigationHeaderViewController }.first
self.navigationHeaderViewController.delegate = self
self.recommendationsChangedObserver = NotificationCenter.default
.addObserver(
forName: Notification.Name.ksr_recommendationsSettingChanged,
object: nil,
queue: nil
) { [weak self] _ in
self?.viewModel.inputs.didChangeRecommendationsSetting()
}
self.optimizelyConfiguredObserver = NotificationCenter.default
.addObserver(forName: .ksr_optimizelyClientConfigured, object: nil, queue: nil) { [weak self] _ in
self?.viewModel.inputs.optimizelyClientConfigured()
}
self.optimizelyConfigurationFailedObserver = NotificationCenter.default
.addObserver(
forName: .ksr_optimizelyClientConfigurationFailed,
object: nil,
queue: nil
) { [weak self] _ in
self?.viewModel.inputs.optimizelyClientConfigurationFailed()
}
self.viewModel.inputs.viewDidLoad()
}
deinit {
[
self.optimizelyConfiguredObserver,
self.optimizelyConfigurationFailedObserver,
self.recommendationsChangedObserver
].forEach { $0.doIfSome(NotificationCenter.default.removeObserver) }
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.viewModel.inputs.viewWillAppear(animated: animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func bindViewModel() {
super.bindViewModel()
self.viewModel.outputs.configureNavigationHeader
.observeForControllerAction()
.observeValues { [weak self] in self?.navigationHeaderViewController.configureWith(params: $0) }
self.viewModel.outputs.configurePagerDataSource
.observeForControllerAction()
.observeValues { [weak self] in self?.configurePagerDataSource($0) }
self.viewModel.outputs.configureSortPager
.observeForControllerAction()
.observeValues { [weak self] in self?.sortPagerViewController.configureWith(sorts: $0) }
self.viewModel.outputs.loadFilterIntoDataSource
.observeForControllerAction()
.observeValues { [weak self] in self?.dataSource?.load(filter: $0) }
self.viewModel.outputs.navigateToSort
.observeForControllerAction()
.observeValues { [weak self] sort, direction in
guard let controller = self?.dataSource?.controllerFor(sort: sort) else { return }
self?.pageViewController.ksr_setViewControllers(
[controller], direction: direction, animated: true, completion: nil
)
}
self.viewModel.outputs.selectSortPage
.observeForControllerAction()
.observeValues { [weak self] in self?.sortPagerViewController.select(sort: $0) }
self.viewModel.outputs.sortsAreEnabled
.observeForUI()
.observeValues { [weak self] in
self?.sortPagerViewController.setSortPagerEnabled($0)
self?.setPageViewControllerScrollEnabled($0)
}
self.viewModel.outputs.updateSortPagerStyle
.observeForControllerAction()
.observeValues { [weak self] in self?.sortPagerViewController.updateStyle(categoryId: $0) }
}
internal func filter(with params: DiscoveryParams) {
self.viewModel.inputs.filter(withParams: params)
}
internal func setSortsEnabled(_ enabled: Bool) {
self.viewModel.inputs.setSortsEnabled(enabled)
}
fileprivate func configurePagerDataSource(_ sorts: [DiscoveryParams.Sort]) {
self.dataSource = DiscoveryPagesDataSource(sorts: sorts)
self.pageViewController.dataSource = self.dataSource
self.pageViewController.ksr_setViewControllers(
[self.dataSource?.controllerFor(index: 0)].compact(),
direction: .forward,
animated: false,
completion: nil
)
}
private func setPageViewControllerScrollEnabled(_ enabled: Bool) {
self.pageViewController.dataSource = enabled == false ? nil : self.dataSource
}
}
extension DiscoveryViewController: UIPageViewControllerDelegate {
internal func pageViewController(
_: UIPageViewController,
didFinishAnimating _: Bool,
previousViewControllers _: [UIViewController],
transitionCompleted completed: Bool
) {
self.viewModel.inputs.pageTransition(completed: completed)
}
internal func pageViewController(
_: UIPageViewController,
willTransitionTo pendingViewControllers: [UIViewController]
) {
guard let dataSource = self.dataSource,
let idx = pendingViewControllers.first.flatMap(dataSource.indexFor(controller:)) else { return }
self.viewModel.inputs.willTransition(toPage: idx)
}
}
extension DiscoveryViewController: SortPagerViewControllerDelegate {
internal func sortPager(_: UIViewController, selectedSort sort: DiscoveryParams.Sort) {
self.viewModel.inputs.sortPagerSelected(sort: sort)
}
}
extension DiscoveryViewController: DiscoveryNavigationHeaderViewDelegate {
func discoveryNavigationHeaderFilterSelectedParams(_ params: DiscoveryParams) {
self.filter(with: params)
}
}
extension DiscoveryViewController: TabBarControllerScrollable {
func scrollToTop() {
if let scrollView = self.pageViewController?.viewControllers?.first?.view as? UIScrollView {
scrollView.scrollToTop()
}
}
}
| apache-2.0 | dca288b7980e3f74853372a35db278d9 | 33.164948 | 104 | 0.744418 | 5.130031 | false | true | false | false |
antonio081014/LeeCode-CodeBase | Swift/insert-into-a-binary-search-tree.swift | 2 | 2266 | /**
* https://leetcode.com/problems/insert-into-a-binary-search-tree/
*
*
*/
// Date: Tue Oct 6 08:59:38 PDT 2020
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
func insertIntoBST(_ root: TreeNode?, _ val: Int) -> TreeNode? {
guard let root = root else { return TreeNode(val) }
if root.val < val {
root.right = insertIntoBST(root.right, val)
} else {
root.left = insertIntoBST(root.left, val)
}
return root
}
}/**
* https://leetcode.com/problems/insert-into-a-binary-search-tree/
*
*
*/
// Date: Tue Oct 6 09:17:54 PDT 2020
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
func insertIntoBST(_ root: TreeNode?, _ val: Int) -> TreeNode? {
if root == nil { return TreeNode(val) }
var node = root
while let cnode = node {
if cnode.val <= val {
if cnode.right != nil {
node = cnode.right
} else {
node?.right = TreeNode(val)
break
}
} else {
if cnode.left != nil {
node = cnode.left
} else {
node?.left = TreeNode(val)
break
}
}
}
return root
}
} | mit | 8a2761d16e33c2537d70d037d0c93575 | 28.828947 | 85 | 0.498235 | 3.672609 | false | false | false | false |
bmichotte/HSTracker | HSTracker/UIs/DeckManager/SaveDeck.swift | 1 | 1689 | //
// SaveDeck.swift
// HSTracker
//
// Created by Benjamin Michotte on 24/03/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import CleanroomLogger
import RealmSwift
import AppKit
protocol SaveDeckDelegate: class {
func deckSaveSaved()
func deckSaveCanceled()
}
class SaveDeck: NSWindowController {
@IBOutlet weak var deckName: NSTextField!
var deck: Deck?
var cards: [Card]?
var exists = false
weak private var _delegate: SaveDeckDelegate?
func setDelegate(_ delegate: SaveDeckDelegate) {
_delegate = delegate
}
override func windowDidLoad() {
super.windowDidLoad()
deckName.stringValue = deck!.name
if RealmHelper.getDeck(with: deck!.deckId) != nil {
exists = true
} else {
Log.error?.message("Can not fetch deck")
}
}
// MARK: - Actions
@IBAction func save(_ sender: AnyObject) {
guard let deck = deck, let cards = cards, cards.isValidDeck() else { return }
RealmHelper.rename(deck: deck, to: deckName.stringValue)
self.saveDeck(update: exists)
}
@IBAction func cancel(_ sender: AnyObject) {
self._delegate?.deckSaveCanceled()
}
func saveDeck(update: Bool) {
guard let deck = deck, let cards = cards, cards.isValidDeck() else { return }
RealmHelper.update(deck: deck, with: cards)
RealmHelper.add(deck: deck, update: update)
NotificationCenter.default.post(name: Notification.Name(rawValue: "reload_decks"),
object: deck)
self._delegate?.deckSaveSaved()
}
}
| mit | b5df03baac5c89c7678954a7649b2aef | 24.19403 | 90 | 0.624408 | 4.317136 | false | false | false | false |
stephentyrone/swift | test/SILOptimizer/pgo_si_reduce.swift | 5 | 2196 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_si_reduce -o %t/main
// This unusual use of 'sh' allows the path of the profraw file to be
// substituted by %target-run.
// RUN: %target-run sh -c 'env LLVM_PROFILE_FILE=$1 $2' -- %t/default.profraw %t/main
// RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata
// RUN: %target-swift-frontend %s -profile-use=%t/default.profdata -emit-sorted-sil -emit-sil -module-name pgo_si_reduce -o - | %FileCheck %s --check-prefix=SIL
// RUN: %target-swift-frontend %s -profile-use=%t/default.profdata -O -emit-sorted-sil -emit-sil -module-name pgo_si_reduce -o - | %FileCheck %s --check-prefix=SIL-OPT
// REQUIRES: profile_runtime
// REQUIRES: executable_test
// REQUIRES: OS=macosx
public func bar(_ x: Int32) -> Int32 {
if (x == 0) {
return 42
}
if (x == 1) {
return 6
}
if (x == 2) {
return 9
}
if (x % 2 == 0) {
return 4242
}
var ret : Int32 = 0
for currNum in stride(from: 5, to: x, by: 5) {
ret += currNum
}
return ret
}
// SIL-LABEL: sil @$s13pgo_si_reduce3fooyys5Int32VF : $@convention(thin) (Int32) -> () !function_entry_count(1) {
// SIL-OPT-LABEL: sil @$s13pgo_si_reduce3fooyys5Int32VF : $@convention(thin) (Int32) -> () !function_entry_count(1) {
public func foo(_ x: Int32) {
// SIL: switch_enum {{.*}} : $Optional<Int32>, case #Optional.some!enumelt: {{.*}} !case_count(100), case #Optional.none!enumelt: {{.*}} !case_count(1)
// SIL: cond_br {{.*}}, {{.*}}, {{.*}} !true_count(50)
// SIL: cond_br {{.*}}, {{.*}}, {{.*}} !true_count(1)
// SIL-OPT: integer_literal $Builtin.Int32, 4242
// SIL-OPT: integer_literal $Builtin.Int32, 42
// SIL-OPT: function_ref @$s13pgo_si_reduce3barys5Int32VADF : $@convention(thin) (Int32) -> Int32
var sum : Int32 = 0
for index in 1...x {
if (index % 2 == 0) {
sum += bar(index)
}
if (index == 50) {
sum += bar(index)
}
sum += 1
}
print(sum)
}
// SIL-LABEL: } // end sil function '$s13pgo_si_reduce3fooyys5Int32VF'
// SIL-OPT-LABEL: } // end sil function '$s13pgo_si_reduce3fooyys5Int32VF'
foo(100)
| apache-2.0 | 67e9064158d82d5a3a62f4f5a9410ace | 35 | 167 | 0.621129 | 2.829897 | false | false | false | false |
Yoloabdo/REST-Udemy | REST apple/REST apple/DetailsViewController.swift | 1 | 3437 | //
// DetailsViewController.swift
// REST apple
//
// Created by Abdulrhman eaita on 4/10/16.
// Copyright © 2016 Abdulrhman eaita. All rights reserved.
//
import UIKit
import AVKit
import AVFoundation
class DetailsViewController: UIViewController {
@IBOutlet weak var vNameLabel: UILabel!
@IBOutlet weak var songImageView: UIImageView!
@IBOutlet weak var rightsLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var genereLabel: UILabel!
var video: Videos?
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updateFonts), name: UIContentSizeCategoryDidChangeNotification, object: nil)
}
func updateUI() {
if let vid = video {
vNameLabel.text = vid._vname
rightsLabel.text = vid._vRights
priceLabel.text = vid._vPrice
genereLabel.text = vid._vGenere
if let data = vid.vImageData {
songImageView.image = UIImage(data: data)
}else {
songImageView.image = UIImage(named: "NotAvilable")
}
}
}
@IBAction func shareButton(sender: UIBarButtonItem) {
shareMedia()
}
@IBAction func playVideo(sender: UIBarButtonItem) {
guard let url = NSURL(string: (video?._vVideoURL)!) else {
print("couldn't load video URL")
return
}
let player = AVPlayer(URL: url)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) {
playerViewController.player?.play()
}
}
func shareMedia(){
let activity1 = "Have you had the opportunity to see this Music Video?"
let activity2 = "\(video?._vname) by \(video?._vArtist)"
let activity3 = "Watch it and tell me what do you think?"
let activity4 = video?._vLinkITunes
let activity5 = "(Shared with the Music Video App!)"
let activityViewController = UIActivityViewController(activityItems: [activity1,activity2, activity3, activity4!, activity5], applicationActivities: nil)
// to stop sharing to any service
// activityViewController.excludedActivityTypes = [UIActivityTypeMail]
activityViewController.completionWithItemsHandler = {
(activity, success, items, error) in
if activity == UIActivityTypeMail {
print("email selected")
}
}
self.presentViewController(activityViewController, animated: true, completion: nil)
}
func updateFonts() {
vNameLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleTitle1)
rightsLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
priceLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
genereLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIContentSizeCategoryDidChangeNotification, object: nil)
}
}
| mit | 6156753607f1d7f8b7c55ce7e58f3177 | 30.522936 | 161 | 0.627765 | 5.42812 | false | false | false | false |
hemant3370/HSPicker | HSPicker.swift | 1 | 12879 | //
// HSPicker.swift
// HSPicker
//
// Created by Hemant Singh on 26/05/16.
// Copyright © 2016 Hemant Singh. All rights reserved.
//
import UIKit
import SwiftyJSON
import ChameleonFramework
class HSEntity: NSObject {
let name: String
var section: Int?
init(name: String) {
self.name = name
}
}
public struct HSSection {
var entities: [HSEntity] = []
mutating func addEntity(entity: HSEntity) {
entities.append(entity)
}
}
public protocol HSPickerDelegate: class {
func entityPicker(picker: HSPicker, didSelectEntityWithName name: String)
func entityPicker(picker: HSPicker, didUnSelectEntityWithName name: String)
}
public class HSPicker: UITableViewController, UINavigationBarDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
var dataSource: [String]! = []
public var listNameForSocket : String!
public var selectedItems : [String]?
public var tag : Int!
public var selectionLimit : Int!
private var searchController: UISearchController!
private var filteredList = [HSEntity]()
private var unsourtedEntities : [HSEntity] {
var unsortedEntities = [HSEntity]()
let data = dataSource
for entity in data! {
let entity = HSEntity(name: entity)
unsortedEntities.append(entity)
}
return unsortedEntities
}
private var _sections: [HSSection]?
private var sections: [HSSection] {
if _sections != nil {
return _sections!
}
let entities: [HSEntity] = unsourtedEntities.map { entity in
let entity = HSEntity(name: entity.name)
entity.section = collation.sectionForObject(entity, collationStringSelector: Selector("name"))
return entity
}
// create empty sections
var sections = [HSSection]()
for _ in 0..<self.collation.sectionIndexTitles.count {
sections.append(HSSection())
}
// put each entity in a section
for entity in entities {
sections[entity.section!].addEntity(entity)
}
// sort each section
for section in sections {
var s = section
s.entities = collation.sortedArrayFromArray(section.entities, collationStringSelector: Selector("name")) as! [HSEntity]
}
_sections = sections
return _sections!
}
private let collation = UILocalizedIndexedCollation.currentCollation()
as UILocalizedIndexedCollation
public weak var delegate: HSPickerDelegate?
public var backImage : UIImage!
public var didSelectEntityClosure: ((String) -> ())?
convenience public init(completionHandler: ((String) -> ())) {
self.init()
self.didSelectEntityClosure = completionHandler
}
override public func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView
visualEffectView.frame = CGRectMake(0, 0, view.bounds.width, view.bounds.height + 30)
tableView.backgroundColor = .clearColor()
view.backgroundColor = .clearColor()
// GradientColor(.LeftToRight, frame: view.frame, colors: [UIColor.flatSkyBlueColor(),UIColor.flatLimeColor()])
if backImage != nil {
tableView.backgroundView = UIImageView(image: backImage)
}
tableView.backgroundView?.addSubview(visualEffectView)
tableView.separatorStyle = .None
tableView.reloadData()
tableView.separatorEffect = UIVibrancyEffect(forBlurEffect: UIBlurEffect(style: .Light))
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)
self.navigationController!.navigationBar.topItem!.title = ""
tableView.emptyDataSetDelegate = self
tableView.emptyDataSetSource = self
for str in self.selectedItems! {
selectedItems![(selectedItems?.indexOf(str))!] = str.lowercaseString
}
}
func btn_clicked(sender: UIBarButtonItem) {
// Do something
self.dismissViewControllerAnimated(true, completion: nil)
}
// func animateTable() {
//
// self.tableView.reloadData()
//
// let cells = tableView.visibleCells
// let tableHeight: CGFloat = tableView.bounds.size.height
//
// for (index, cell) in cells.enumerate() {
// cell.transform = CGAffineTransformMakeTranslation(0, tableHeight)
// UIView.animateWithDuration(1.0, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
// cell.transform = CGAffineTransformMakeTranslation(0, 0);
// }, completion: nil)
// }
// }
public override func viewDidAppear(animated: Bool) {
createSearchBar()
searchController.searchBar.becomeFirstResponder()
}
public override func viewWillDisappear(animated: Bool) {
// Clear the Search bar text
searchController.active = false
self.clearAllNotice()
// Dismiss the search tableview
searchController.dismissViewControllerAnimated(true) {
}
}
// MARK: Methods
public func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! {
let title : NSMutableAttributedString = NSMutableAttributedString(string: "No matches found.")
title.addAttribute(NSForegroundColorAttributeName, value: UIColor.flatBlackColor(), range: NSRange.init(location: 0, length: 17))
return title
}
private func createSearchBar() {
// self.navigationController?.navigationBarHidden = true
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
// tableView.tableHeaderView = searchController.searchBar
self.navigationItem.titleView = searchController.searchBar
searchController.searchBar.searchBarStyle = UISearchBarStyle.Prominent
searchController.searchBar.barTintColor = UIColor.whiteColor()
searchController.searchBar.tintColor = UIColor.whiteColor()
searchController.searchBar.backgroundColor = UIColor.clearColor()
// UIColor(hex: 0x0C94C2)
searchController.searchBar.showsBookmarkButton = false
searchController.searchBar.showsCancelButton = false
// searchController.active = true
searchController.hidesNavigationBarDuringPresentation = false
if self.navigationController == nil{
self.tableView.frame = CGRectMake(0, 64, view.frame.size.width, view.frame.size.height - 64)
// }
}
}
private func filter(searchText: String) -> [HSEntity] {
filteredList.removeAll()
sections.forEach { (section) -> () in
section.entities.forEach({ (entity) -> () in
if entity.name.characters.count >= searchText.characters.count {
let result = entity.name.compare(searchText, options: [.CaseInsensitiveSearch, .DiacriticInsensitiveSearch], range: searchText.startIndex ..< searchText.endIndex)
if (result == .OrderedSame) {
filteredList.append(entity)
}
}
})
}
return filteredList.count == 0 ? [] : filteredList
}
}
// MARK: - Table view data source
extension HSPicker {
override public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// if searchController.searchBar.isFirstResponder() {
return 1
// }
// return sections.count
}
public override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// if searchController.searchBar.isFirstResponder() {
// return filteredList.count
// }
// return sections[section].entities.count
return (dataSource?.count)!
}
override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var tempCell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("UITableViewCell")
if tempCell == nil {
tempCell = UITableViewCell(style: .Default, reuseIdentifier: "UITableViewCell")
}
let cell: UITableViewCell! = tempCell
cell.contentView.alpha = 0.9
cell.backgroundColor = .clearColor()
return cell
}
public override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let entity : String = dataSource![indexPath.row]
// if searchController.searchBar.isFirstResponder() {
// entity = filteredList[indexPath.row]
// } else {
// entity = sections[indexPath.section].entities[indexPath.row]
// }
cell.textLabel?.text = dataSource[indexPath.row].stringByReplacingOccurrencesOfString("_", withString: " ").capitalizedString
// .stringByReplacingOccurrencesOfString("skills_", withString: "").stringByReplacingOccurrencesOfString("locations_", withString: "")
cell.textLabel?.textColor = UIColor.flatGrayColorDark()
if ((selectedItems?.contains(entity.lowercaseString)) == true) {
cell.accessoryType = .Checkmark
}
else{
cell.accessoryType = .None
}
}
// override public func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
// return collation.sectionIndexTitles
// }
//
//
//
// override public func tableView(tableView: UITableView,
// sectionForSectionIndexTitle title: String,
// atIndex index: Int)
// -> Int {
// return collation.sectionForSectionIndexTitleAtIndex(index)
// }
}
// MARK: - Table view delegate
extension HSPicker {
override public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let entity = dataSource![indexPath.row]
// if searchController.searchBar.isFirstResponder() {
// entity = filteredList[indexPath.row]
// } else {
// entity = sections[indexPath.section].entities[indexPath.row]
//
// }
if selectedItems?.count < selectionLimit || tableView.cellForRowAtIndexPath(indexPath)?.accessoryType == .Checkmark {
tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = tableView.cellForRowAtIndexPath(indexPath)?.accessoryType == .Checkmark ? .None : .Checkmark
if tableView.cellForRowAtIndexPath(indexPath)?.accessoryType == .Checkmark {
selectedItems?.append(entity)
delegate?.entityPicker(self, didSelectEntityWithName: entity)
}
else {
selectedItems?.removeAtIndex((selectedItems?.indexOf(entity))!)
delegate?.entityPicker(self, didUnSelectEntityWithName: entity)
}
}
if selectedItems?.count >= selectionLimit {
self.view.endEditing(true)
}
// self.navigationController?.popViewControllerAnimated(true)
}
}
// MARK: - UISearchDisplayDelegate
extension HSPicker: UISearchResultsUpdating {
public func updateSearchResultsForSearchController(searchController: UISearchController) {
filter(searchController.searchBar.text!)
if searchController.searchBar.text!.characters.count > 0 {
self.pleaseWait()
WebUtil.sharedInstance().get("/\(listNameForSocket)?query=" + searchController.searchBar.text! , completion: { (result) in
self.dataSource = []
print(result["data"].stringValue)
for obj : JSON in result["data"].arrayValue{
self.dataSource.append(obj.stringValue)
}
self.clearAllNotice()
self.tableView.reloadData()
})
}
}
}
| mit | c2a5f9633cf3f2d35e4d31b81571c8e8 | 35.585227 | 178 | 0.633561 | 5.361366 | false | false | false | false |
gongmingqm10/SwiftTraining | Wechat/Wechat/MomentDetailController.swift | 1 | 1043 | //
// MomentDetailController.swift
// Wechat
//
// Created by Ming Gong on 6/18/15.
// Copyright © 2015 gongmingqm10. All rights reserved.
//
import UIKit
class MomentDetailController: UIViewController {
@IBOutlet weak var momentImage: UIImageView!
@IBOutlet weak var momentTitle: UILabel!
@IBOutlet weak var momentContent: UILabel!
var moment: Moment?
override func viewDidLoad() {
self.momentImage.layer.cornerRadius = self.momentImage.bounds.width / 2.0
self.momentImage.clipsToBounds = true
self.momentTitle.text = moment?.title
self.momentContent.text = moment?.content
let defaultAvatar = UIImage(named: "DefaultAvatar")
if let imageUrl = moment?.imageHref {
self.momentImage.sd_setImageWithURL(NSURL(string: imageUrl))
self.momentImage.sd_setImageWithURL(NSURL(string: imageUrl), placeholderImage: defaultAvatar)
} else {
self.momentImage.image = defaultAvatar
}
}
}
| mit | 6beab17dfb564b68fcc2648127831b02 | 28.771429 | 105 | 0.661228 | 4.415254 | false | false | false | false |
USAssignmentWarehouse/EnglishNow | EnglishNow/View/Cell/CellOfTimeLineVC.swift | 1 | 8779 | //
// CellOfTimeLineVC.swift
// EnglishNow
//
// Created by Nha T.Tran on 5/21/17.
// Copyright © 2017 IceTeaViet. All rights reserved.
//
import UIKit
import Firebase
import FirebaseDatabase
class CellOfTimeLineVC: UITableViewCell {
let avatar: UIImageView = {
let imageview = UIImageView()
imageview.image = UIImage(named: ResourceName.avatarPlaceholder)
imageview.translatesAutoresizingMaskIntoConstraints = false
imageview.layer.cornerRadius = 16
imageview.layer.masksToBounds = true
imageview.contentMode = .scaleAspectFill
return imageview
}()
let photo: UIImageView = {
let imageview = UIImageView()
imageview.image = UIImage(named: ResourceName.avatarPlaceholder)
imageview.translatesAutoresizingMaskIntoConstraints = false
imageview.layer.cornerRadius = 16
imageview.layer.masksToBounds = true
imageview.contentMode = .scaleAspectFill
return imageview
}()
let btnLike: UIButton = {
let btn = UIButton()
btn.imageView?.image = UIImage(named: "like.png")
btn.translatesAutoresizingMaskIntoConstraints = false
return btn
}()
let txtName: UILabel = {
let label = UILabel()
label.text = "Hello"
label.textAlignment = NSTextAlignment.left
label.font = UIFont(name:"HelveticaNeue-Bold", size: 18.0)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let txtTime: UILabel = {
let label = UILabel()
label.text = ""
label.textAlignment = NSTextAlignment.left
label.textColor = UIColor.lightGray
label.font = UIFont(name: "Arial" , size: 16)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let txtNumberOfLike: UILabel = {
let label = UILabel()
label.text = "0"
label.textAlignment = NSTextAlignment.right
label.font = UIFont(name: "Arial" , size: 15)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let txtContent: UILabel = {
let label = UILabel()
label.text = ""
label.textAlignment = NSTextAlignment.left
label.font = UIFont(name: "Arial" , size: 17)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var photoBigHeightAnchor: NSLayoutConstraint?
var photoSmallHeightAnchor: NSLayoutConstraint?
var status: Status?
override func awakeFromNib() {
super.awakeFromNib()
initShow()
// Initialization code
}
func initShow(){
avatar.layer.masksToBounds = true
avatar.layer.cornerRadius = 10
self.addSubview(avatar)
self.addSubview(txtName)
self.addSubview(txtTime)
self.addSubview(btnLike)
self.addSubview(txtNumberOfLike)
self.addSubview(txtContent)
self.addSubview(photo)
avatar.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true
avatar.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true
avatar.widthAnchor.constraint(equalToConstant: 56).isActive = true
avatar.heightAnchor.constraint(equalToConstant: 56).isActive = true
txtName.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true
txtName.leftAnchor.constraint(equalTo: avatar.rightAnchor, constant: 8).isActive = true
txtName.heightAnchor.constraint(equalToConstant: 24).isActive = true
txtName.rightAnchor.constraint(equalTo: txtNumberOfLike.leftAnchor, constant: -8).isActive = true
txtTime.topAnchor.constraint(equalTo: txtName.bottomAnchor, constant: 8).isActive = true
txtTime.leftAnchor.constraint(equalTo: avatar.rightAnchor, constant: 8).isActive = true
txtTime.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
txtTime.heightAnchor.constraint(equalToConstant: 24).isActive = true
txtContent.topAnchor.constraint(equalTo: txtTime.bottomAnchor, constant: 8).isActive = true
txtContent.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 72).isActive = true
txtContent.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
photoBigHeightAnchor = photo.heightAnchor.constraint(equalToConstant: 100)
photoSmallHeightAnchor = photo.heightAnchor.constraint(equalToConstant: 1)
photo.topAnchor.constraint(equalTo: txtContent.bottomAnchor, constant: 8).isActive = true
photo.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 72).isActive = true
photo.widthAnchor.constraint(equalToConstant: 150).isActive = true
photo.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -8).isActive = true
btnLike.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true
btnLike.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
btnLike.widthAnchor.constraint(equalToConstant: 24).isActive = true
btnLike.heightAnchor.constraint(equalToConstant: 24).isActive = true
txtNumberOfLike.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true
txtNumberOfLike.rightAnchor.constraint(equalTo: btnLike.leftAnchor, constant: -8).isActive = true
txtNumberOfLike.widthAnchor.constraint(equalToConstant: 76).isActive = true
txtNumberOfLike.heightAnchor.constraint(equalToConstant: 20).isActive = true
onClickBtnLike()
}
func onClickBtnLike (){
btnLike.addTarget(self, action: #selector(onClick), for: .touchUpInside)
}
func onClick(btn: UIButton) {
if (status?.isUserLiked == false){
if let user = Auth.auth().currentUser{
Database.database().reference().child("status").child((status?.statusId)!).child("like").child(user.uid).setValue(true)
var likeNumber = (status?.likeNumber)! + 1
Database.database().reference().child("status").child((status?.statusId)!).child("like_number").setValue(likeNumber)
txtNumberOfLike.text = "\(likeNumber)"
print("status?.user: \(status?.user)")
print("status?.statusId: \(status?.statusId)")
print("user.uid: \(user.uid)")
Database.database().reference().child("user_profile").child((status?.user)!).child("status").child((status?.statusId)!).child("like").child(user.uid).setValue(true)
Database.database().reference().child("user_profile").child((status?.user)!).child("status").child((status?.statusId)!).child("like_number").setValue(likeNumber)
status?.isUserLiked = true
status?.likeNumber = likeNumber
btnLike.setBackgroundImage(UIImage(named: "liked.png"), for: UIControlState.normal)
}
}
else {
if let user = Auth.auth().currentUser{
Database.database().reference().child("status").child((status?.statusId)!).child("like").child(user.uid).setValue(false)
var likeNumber = (status?.likeNumber)! - 1
Database.database().reference().child("status").child((status?.statusId)!).child("like_number").setValue(likeNumber)
txtNumberOfLike.text = "\(likeNumber)"
Database.database().reference().child("user_profile").child((status?.user)!).child("status").child((status?.statusId)!).child("like").child(user.uid).setValue(false)
Database.database().reference().child("user_profile").child((status?.user)!).child("status").child((status?.statusId)!).child("like_number").setValue(likeNumber)
status?.isUserLiked = false
status?.likeNumber = likeNumber
btnLike.setBackgroundImage(UIImage(named: "like.png"), for: UIControlState.normal)
}
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| apache-2.0 | 111a56cf68ac86f5ac8d7facf3a85779 | 38.1875 | 181 | 0.625085 | 5.225 | false | false | false | false |
dwestgate/AdScrubber | AdScrubber/BlackholeList.swift | 1 | 19665 | //
// BlackholeList.swift
// AdScrubber
//
// Created by David Westgate on 12/31/15.
// Copyright © 2016 David Westgate
//
// 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 SwiftyJSON
import SafariServices
/// Provides functions for downloading and creating JSON ContentBlocker lists
struct BlackholeList {
// MARK: -
// MARK: Metadata Handling
/// Stores metadata associated with a blacklist
struct Blacklist {
/// The name of the blacklist
fileprivate let name: String
/**
Writes the metadata for a new blacklist to the default store
- Parameters:
- value: The name of the list
- url: The list's URL
- fileType: The format of file containing the list (JSON, hosts, or built-in)
- entryCount: The number of rules in the list
- etag: The HTML etag value of the list at its URL
*/
init(withListName value: String, url: String, fileType: String, entryCount: String, etag: String) {
name = value
setValueWithKey(url, forKey: "URL")
setValueWithKey(fileType, forKey: "FileType")
setValueWithKey(entryCount, forKey: "EntryCount")
setValueWithKey(etag, forKey: "Etag")
}
/**
Writes the metadata for a new blacklist to the default store
- Parameters:
- withListName: The name of the list
- url: The list's URL
- fileType: The format of file containing the list (JSON, hosts, or built-in)
*/
init(withListName: String, url: String, fileType: String) {
name = withListName
setValueWithKey(url, forKey: "URL")
setValueWithKey(fileType, forKey: "FileType")
}
/**
Writes the metadata for a new blacklist to the default store
- Parameters:
- withListName: The name of the list
*/
init(withListName: String) {
name = withListName
}
/**
Given a key, returns the stored default value of that key or nil
- Parameters:
- key: The key for the value to be returned
- Returns: The stored value or nil
*/
func getValueForKey(_ key: String) -> String? {
if let value = defaultContainer.object(forKey: "\(name)Blacklist\(key)") as? String {
return value
} else {
return nil
}
}
/**
Given a key value pair, writes the value to the default store
- Parameters:
- value: The value to be stored
- forKey: The key to be employed for writing the value
*/
func setValueWithKey(_ value: String, forKey: String) {
defaultContainer.set(value, forKey: "\(name)Blacklist\(forKey)")
}
/**
Given a key, deletes from the store the key value pair
- Parameters:
- key: The key of the key value pair to be deleted
*/
func removeValueForKey(_ key: String) {
defaultContainer.removeObject(forKey: "\(name)\(key)")
}
/**
Deletes all key value pairs that have been written to the
default store that are associated with the list
*/
func removeAllValues() {
removeValueForKey("URL")
removeValueForKey("FileType")
removeValueForKey("EntryCount")
removeValueForKey("Etag")
}
}
// MARK: Constants
/// Convenience var for accessing group.com.refabricants.adscrubber
fileprivate static let sharedContainer = UserDefaults.init(suiteName: "group.com.refabricants.adscrubber")
/// Convenience var for accessing the default container
fileprivate static let defaultContainer = UserDefaults.standard
// MARK: Variables
/// Metadata for the bundled ContentBlocker blocklist
static var preloadedBlacklist = Blacklist(withListName: "preloaded", url: "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts", fileType: "built-in", entryCount: "27167", etag: "9011c48902c695e9a92b259a859f971f7a9a5f75")
/// Metadata for the currently loaded custom blocklist
static var currentBlacklist = Blacklist(withListName: "current")
/// Metadata for the blacklist stored in the TextView
static var displayedBlacklist = Blacklist(withListName: "displayed")
/// Metadata for the blacklist stored in the TextView but not yet validated or loaded
static var candidateBlacklist = Blacklist(withListName: "candidate")
// TODO: Move these to ViewController
// MARK: List Metadata Getters/Setters
/**
Reads the value in the shared storage container that determines whether
or not a blacklist should be used. Returns the value or, if no value is
found in shared storage, sets it to false and returns false.
- Returns: A boolean value indicating whether or not a custom blacklist
should be used
*/
static func getIsUseCustomBlocklistOn() -> Bool {
if let value = sharedContainer!.bool(forKey: "isUseCustomBlocklistOn") as Bool? {
return value
} else {
let value = false
sharedContainer!.set(value, forKey: "isUseCustomBlocklistOn")
return value
}
}
/**
Sets the value in the shared storage container that determines whether
or not a custom blacklist shouldbe used
- Parameters:
- value: True if a custom blacklist should be used, false otherwise
*/
static func setIsUseCustomBlocklistOn(_ value: Bool) {
sharedContainer!.set(value, forKey: "isUseCustomBlocklistOn")
}
/**
Reads the value in the shared storage container that contains the
blacklist file type. Returns the file type (i.e. "built-in", "JSON",
or "hosts" or, if no value is found in shared storage, sets the
value to "none."
- Returns: The file type of the currently-loaded blacklist, or "none"
*/
static func getDownloadedBlacklistType() -> String {
if let value = sharedContainer!.object(forKey: "downloadedBlacklistType") as? String {
return value
} else {
let value = "none"
sharedContainer!.set(value, forKey: "downloadedBlacklistType")
return value
}
}
/**
Sets the value in the shared storage container that contains the
blacklist file type.
- Parameters:
- value: The file type of the blacklist (i.e. "built-in", "JSON",
or "hosts")
*/
static func setDownloadedBlacklistType(_ value: String) {
sharedContainer!.set(value, forKey: "downloadedBlacklistType")
}
/**
Reads the value in the shared storage container that indicates whether
a new blacklist is in the process of being downloaded. Returns the value
or, if no value is found in shared storage, sets it to false and returns
false.
- Returns: A boolean value indicating whether or not a blacklist is
in the process of being downloaded
*/
static func getIsReloading() -> Bool {
if let value = sharedContainer!.bool(forKey: "isReloading") as Bool? {
return value
} else {
let value = false
sharedContainer!.set(value, forKey: "isReloading")
return value
}
}
/**
Sets the value in the shared storage container that indicates whether
or not a new blacklist is in the process of being downloaded.
- Parameters:
- value: A boolean value indicating whether or not a blacklist is
in the process of being downloaded
*/
static func setIsReloading(_ value: Bool) {
sharedContainer!.set(value, forKey: "isReloading")
}
/**
Reads the value in the shared storage container that indicates whether
the "wildcardBlockerList.json" file should be loaded instead of the
default "blockerList.json" file.
- Returns: A boolean value indicating whether or not the
"wildcardBlockerList.json" file should be loaded
*/
static func getIsBlockingSubdomains() -> Bool {
if let value = sharedContainer!.bool(forKey: "isBlockSubdomainsOn") as Bool? {
return value
} else {
let value = false
sharedContainer!.set(value, forKey: "isBlockSubdomainsOn")
return value
}
}
/**
Sets the value in the shared storage container that indicates whether
the "wildcardBlockerList.json" file should be loaded instead of the
default "blockerList.json" file.
- Parameters:
- value: A boolean value indicating whether or not the
"wildcardBlockerList.json" file should be loaded
*/
static func setIsBlockingSubdomains(_ value: Bool) {
sharedContainer!.set(value, forKey: "isBlockSubdomainsOn")
}
// MARK: BlackholeList Functions
/**
Fetches information on the URL of a blacklist and determines
whether or not the blacklist can and should be downloaded.
If the file can be downloaded, "should be downloaded" is
determined by comparing the remote file's etag to the etag
in the metadata recorded when the current file was loaded.
- Parameters:
- blacklistURL: The URL of the blacklist to be validated
*/
static func validateURL(_ blacklistURL:URL, completion:((_ updateStatus: ListUpdateStatus) -> ())?) {
setIsReloading(true)
let request = NSMutableURLRequest(url: blacklistURL)
request.httpMethod = "HEAD"
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
var result = ListUpdateStatus.UpdateSuccessful
defer {
if completion != nil {
DispatchQueue.main.async(execute: { () -> Void in
completion!(updateStatus: result)
})
}
}
guard let httpResp: HTTPURLResponse = response as? HTTPURLResponse else {
result = ListUpdateStatus.ServerNotFound
return
}
guard httpResp.statusCode == 200 else {
result = ListUpdateStatus.NoSuchFile
return
}
if let candidateEtag = httpResp.allHeaderFields["Etag"] as? NSString {
if let currentEtag = currentBlacklist.getValueForKey("Etag") {
if candidateEtag.isEqual(currentEtag) {
result = ListUpdateStatus.NoUpdateRequired
} else {
currentBlacklist.setValueWithKey(candidateEtag as String, forKey: "Etag")
}
} else {
currentBlacklist.setValueWithKey(candidateEtag as String, forKey: "Etag")
}
} else {
currentBlacklist.removeValueForKey("Etag")
}
})
task.resume()
}
/**
Downloads a remote blacklist
- Parameters:
- blacklistURL: The URL of the blacklist to be downloaded
- Throws: ListUpdateStatus
- .ErrorDownloading: The download failed
- .ErrorSavingToLocalFilesystem: Saving the downloaded file failed
- Returns: The locally-saved file
*/
static func downloadBlacklist(_ blacklistURL: URL) throws -> URL? {
setIsReloading(true)
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as URL
let localFile = documentDirectory.appendingPathComponent("downloadedBlocklist.txt")
guard let myblacklistURLFromUrl = try? Data(contentsOf: blacklistURL) else {
throw ListUpdateStatus.ErrorDownloading
}
guard (try? myblacklistURLFromUrl.write(to: localFile, options: [.atomic])) != nil else {
throw ListUpdateStatus.ErrorSavingToLocalFilesystem
}
return localFile
}
/**
If the downloaed blacklist is a JSON file, replaces the exiting
"blockerList.json" file in the shared container with the downloaded
file.
If the downloaded blacklist is a hosts file, parses the downloaded file
and uses the entries to create both a "blockerList.json" file and
a "wildcardBlockerList.json" file in the shared container. The latter
list adds a wildcard prefix to every rule to block subdomains.
- Parameters:
- blacklist: The URL of the downloaded blacklist
- Returns:
- updateStatus:
- .UpdateSuccessful: The operation was successful
- .InvalidJSON: A JSON file was detected, but the file does not conform to expected Content Blocker syntax
- .ErrorSavingToLocalFilesystem: An error occurred moving the file to the shared container
- .ErrorParsingFile: A hosts file was detected, but the an error occurred while parsing it
- .TooManyEntries: There are more than 50,000 rule entries
- blacklistFileType: "JSON" or "hosts," depending upon which file type was detected
- numberOfEntries: The number of entries detected in the blacklist
*/
static func createBlockerListJSON(_ blacklist: URL) -> (updateStatus: ListUpdateStatus, blacklistFileType: String?, numberOfEntries: Int?) {
setIsReloading(true)
var updateStatus = ListUpdateStatus.UpdateSuccessful
let fileManager = FileManager.default
let sharedFolder = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.refabricants.adscrubber")! as URL
let blockerListURL = sharedFolder.appendingPathComponent("blockerList.json")
let wildcardBlockerListURL = sharedFolder.appendingPathComponent("wildcardBlockerList.json")
var wildcardDomains: Set<String>
var blacklistFileType = "hosts"
var numberOfEntries = 0
var jsonSet = [[String: [String: String]]]()
var jsonWildcardSet = [[String: [String: String]]]()
var blockerListEntry = ""
var wildcardBlockerListEntry = ""
let data = try? Data(contentsOf: blacklist)
if let jsonArray = JSON(data: data!).arrayObject {
if JSONSerialization.isValidJSONObject(jsonArray) {
for element in jsonArray {
guard let newElement = element as? [String : NSDictionary] else {
return (ListUpdateStatus.InvalidJSON, nil, nil)
}
guard newElement.keys.count == 2 else {
return (ListUpdateStatus.InvalidJSON, nil, nil)
}
let hasAction = contains(Array(newElement.keys), text: "action")
let hasTrigger = contains(Array(newElement.keys), text: "trigger")
guard hasAction && hasTrigger else {
return (ListUpdateStatus.InvalidJSON, nil, nil)
}
numberOfEntries++
}
do {
_ = try? fileManager.removeItem(at: blockerListURL)
try fileManager.moveItem(at: blacklist, to: blockerListURL)
} catch {
return (ListUpdateStatus.ErrorSavingToLocalFilesystem, nil, nil)
}
blacklistFileType = "JSON"
}
} else {
let validFirstChars = "01234567890abcdef"
_ = try? FileManager.default.removeItem(atPath: blockerListURL.path)
_ = try? FileManager.default.removeItem(atPath: wildcardBlockerListURL.path)
guard let sr = StreamReader(path: blacklist.path) else {
return (ListUpdateStatus.ErrorParsingFile, nil, nil)
}
guard let blockerListStream = OutputStream(toFileAtPath: blockerListURL.path, append: true) else {
return (ListUpdateStatus.ErrorSavingParsedFile, nil, nil)
}
guard let wildcardBlockerListStream = OutputStream(toFileAtPath: wildcardBlockerListURL.path, append: true) else {
return (ListUpdateStatus.ErrorSavingParsedFile, nil, nil)
}
blockerListStream.open()
wildcardBlockerListStream.open()
defer {
sr.close()
blockerListStream.write("]}}]", maxLength: <#Int#>)
blockerListStream.close()
wildcardBlockerListStream.write("]}}]", maxLength: <#Int#>)
wildcardBlockerListStream.close()
}
var firstPartOfString = "[{\"action\":{\"type\":\"block\"},\"trigger\":{\"url-filter\":\".*\",\"resource-type\":[\"script\"],\"load-type\":[\"third-party\"]}},"
firstPartOfString += "{\"action\":{\"type\":\"block\"},\"trigger\":{\"url-filter\":\".*\",\"if-domain\":["
while let line = sr.nextLine() {
if ((!line.isEmpty) && (validFirstChars.contains(String(line.characters.first!)))) {
var uncommentedText = line
if let commentPosition = line.characters.index(of: "#") {
uncommentedText = line[line.characters.index(line.startIndex, offsetBy: 0)...<#T##String.CharacterView corresponding to `commentPosition`##String.CharacterView#>.index(before: commentPosition)]
}
let lineAsArray = uncommentedText.components(separatedBy: CharacterSet.whitespaces)
let listOfDomainsFromLine = lineAsArray.filter { $0 != "" }
for entry in Array(listOfDomainsFromLine[1..<listOfDomainsFromLine.count]) {
guard let validatedURL = URL(string: "http://" + entry) else { break }
guard let validatedHost = validatedURL.host else { break }
var components = validatedHost.components(separatedBy: ".")
guard components[0].lowercased() != "localhost" else { break }
let domain = components.joined(separator: ".")
numberOfEntries += 1
blockerListEntry = ("\(firstPartOfString)\"\(domain)\"")
wildcardBlockerListEntry = ("\(firstPartOfString)\"*\(domain)\"")
firstPartOfString = ","
blockerListStream.write(blockerListEntry, maxLength: <#Int#>)
wildcardBlockerListStream.write(wildcardBlockerListEntry, maxLength: <#Int#>)
}
}
}
}
_ = try? FileManager.default.removeItem(atPath: blacklist.path)
if numberOfEntries > 50000 {
updateStatus = ListUpdateStatus.TooManyEntries
}
setIsReloading(false)
return (updateStatus, blacklistFileType, numberOfEntries)
}
// MARK: Helper Functions
/**
Ignoring case, determines whether or not an array contains a particular string
- Parameters:
- elements: An arrray of strings
- text: The string to search for
- Returns: **true** if *text* occurs in *elements*, **false** otherwise
*/
static func contains(_ elements: Array<String>, text: String) -> Bool {
for element in elements {
if (element.caseInsensitiveCompare(text) == ComparisonResult.orderedSame) {
return true
}
}
return false
}
}
| mit | ce9d8b002ad0327f6790af2416a6c433 | 35.75514 | 236 | 0.65236 | 4.835014 | false | false | false | false |
manGoweb/MimeLib | Generator/MimeLibGenerator/main.swift | 1 | 3482 | //
// main.swift
// MimeLibGenerator
//
// Created by Ondrej Rafaj on 14/12/2016.
// Copyright © 2016 manGoweb UK Ltd. All rights reserved.
//
import Foundation
// MARK: Start program
print("MimeLibGenerator starting ...\n")
// MARK: Getting arguments
var path: String = ""
var c = 0;
for arg in CommandLine.arguments {
if c == 1 && arg.count > 0 {
path = arg
print("Export path set to: " + path)
}
c += 1
}
let url: URL = URL(string: "http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types")!
let dataString: String = try! String.init(contentsOf: url)
var enumOutput: String = "public enum MimeType: String {\n"
var getExtensionOutput: String = "\tpublic static func get(fileExtension ext: String) -> MimeType? {\n"
getExtensionOutput += "\t\tswitch ext {\n"
var getMimeOutput: String = "\tpublic static func fileExtension(forMime mime: String) -> String? {\n"
getMimeOutput += "\t\tswitch mime {\n"
var usedExtensions = Set<String>()
var mimeToEnum = [String: String]()
func handle(ext: String, mime: String) {
guard !usedExtensions.contains(ext) else {
return
}
usedExtensions.insert(ext)
var enumExt = ext
if Int(ext.substr(0)) != nil || ext == "class" {
enumExt = "_" + ext
}
if enumExt.contains("-") {
let arr = ext.components(separatedBy: "-")
var x = 0
for part in arr {
if x == 0 {
enumExt = part
}
else {
enumExt += part.capitalizingFirstLetter()
}
x += 1
}
}
let enumCase = mimeToEnum[mime] ?? enumExt
mimeToEnum[mime] = enumCase
if enumCase == enumExt {
enumOutput += "\tcase \(enumCase) = \"\(mime)\"\n"
getMimeOutput += "\t\tcase \"\(mime)\":\n"
getMimeOutput += "\t\t\treturn \"\(ext)\"\n"
}
getExtensionOutput += "\t\tcase \"\(ext)\":\n"
getExtensionOutput += "\t\t\treturn .\(enumCase)\n"
}
for line in dataString.lines {
guard line.substr(0) != "#" else {
continue
}
let parts = line.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
.trimmingCharacters(in: .whitespaces)
.components(separatedBy: " ")
guard let mime = parts.first?.lowercased() else {
continue
}
let extensions = parts.dropFirst().map { $0.lowercased() }
for ext in extensions {
handle(ext: ext, mime: mime)
}
}
enumOutput += "}"
getExtensionOutput += "\t\tdefault:\n"
getExtensionOutput += "\t\t\treturn nil\n"
getExtensionOutput += "\t\t}\n"
getExtensionOutput += "\t}\n\n"
getMimeOutput += "\t\tdefault:\n"
getMimeOutput += "\t\t\treturn nil\n"
getMimeOutput += "\t\t}\n"
getMimeOutput += "\t}\n\n"
var mimeOutput: String = "public class Mime {\n\n"
mimeOutput += getExtensionOutput
mimeOutput += getMimeOutput
mimeOutput += "}\n"
if path.count == 0 {
print(enumOutput)
print("\n\n\n")
print(mimeOutput)
}
else {
var enumUrl: URL = URL(fileURLWithPath: path)
enumUrl.appendPathComponent("MimeType.swift")
Updater.write(data: enumOutput, toFile: enumUrl)
var mimeUrl: URL = URL(fileURLWithPath: path)
mimeUrl.appendPathComponent("Mime.swift")
Updater.write(data: mimeOutput, toFile: mimeUrl)
}
print("\nThank you for using MimeLibGenerator!\n\nOndrej Rafaj & team manGoweb UK! (http://www.mangoweb.cz/en)\n\n\n")
Example.run()
| mit | a7a7f7b20af69caa1167097eb7887f6c | 23.864286 | 118 | 0.609595 | 3.477522 | false | false | false | false |
popricoly/Contacts | Sources/Contacts/AppDelegate.swift | 1 | 3719 | //
// AppDelegate.swift
// Contacts
//
// Created by Olexandr Matviichuk on 7/25/17.
// Copyright © 2017 Olexandr Matviichuk. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if UserDefaults.standard.runFirstly {
loadContacts()
UserDefaults.standard.runFirstly = false
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
}
func loadContacts() {
do {
if let contactsJsonPath = Bundle.main.url(forResource: "Contacts", withExtension: "json") {
let data = try Data(contentsOf: contactsJsonPath)
let json = try JSONSerialization.jsonObject(with: data, options: [])
for contactInDictionary in (json as? [Dictionary<String, String>])! {
let firstName = contactInDictionary["firstName"] ?? ""
let lastName = contactInDictionary["lastName"] ?? ""
let phoneNumber = contactInDictionary["phoneNumber"] ?? ""
let streetAddress1 = contactInDictionary["streetAddress1"] ?? ""
let streetAddress2 = contactInDictionary["streetAddress2"] ?? ""
let city = contactInDictionary["city"] ?? ""
let state = contactInDictionary["state"] ?? ""
let zipCode = contactInDictionary["zipCode"] ?? ""
OMContactsStorage.sharedStorage.saveContactWith(firstName: firstName, lastName: lastName, phoneNumber: phoneNumber, StreetAddress1: streetAddress1, StreetAddress2: streetAddress2, city: city, state: state, zipCode: zipCode)
}
}
} catch {
print("\(error.localizedDescription)")
}
}
}
| mit | e3d118e416cd2a5f9bd96e56d27b41fd | 51.366197 | 285 | 0.681011 | 5.599398 | false | false | false | false |
roambotics/swift | test/Generics/issue-58067.swift | 2 | 782 | // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s
// https://github.com/apple/swift/issues/58067
// CHECK-LABEL: .P1@
// CHECK-NEXT: Requirement signature: <Self where Self.[P1]X : P1, Self.[P1]X == Self.[P1]X.[P1]X>
public protocol P1 {
associatedtype X: P1 where X.X == X
}
// CHECK-LABEL: .P2@
// CHECK-NEXT: Requirement signature: <Self where Self : Collection, Self : P1, Self.[Sequence]Element : P1, Self.[P1]X == Self.[P2]Z.[P2]Y, Self.[P2]Y : P3, Self.[P2]Z : P2>
public protocol P2: Collection, P1 where Element: P1, X == Z.Y {
associatedtype Y: P3
associatedtype Z: P2
}
// CHECK-LABEL: .P3@
// CHECK-NEXT: Requirement signature: <Self where Self : P2, Self.[P3]T : P2>
public protocol P3: P2 {
associatedtype T: P2
}
| apache-2.0 | 3379e29ccbbfcefbbe8eb8e0d2c24b2d | 34.545455 | 174 | 0.668798 | 2.715278 | false | false | false | false |
tomduckering/CrosswayESVTools | CrosswayESVTools/ESVXMLParser.swift | 1 | 6851 | //
// ESVXMLParser.swift
// CrosswayESVTools
//
// Created by Tom Duckering on 11/01/2017.
// Copyright © 2017 Tom Duckering. All rights reserved.
//
import Foundation
let NEWLINE = "\n"
let XML_FILE_TYPE = "xml"
enum ESVXMLElement:String {
case BeginChapter = "begin-chapter"
case EndChapter = "end-chapter"
case Reference = "reference"
case Heading = "heading"
case VerseNumber = "verse-num"
case VerseUnit = "verse-unit"
case BeginParagraph = "begin-paragraph"
case EndParagraph = "end-paragraph"
case FootNote = "footnote"
case WordsOfChrist = "woc"
case Italic = "i"
case BeginBlockIndent = "begin-block-indent"
case EndBlockIndent = "end-block-indent"
case BeginLine = "begin-line"
case EndLine = "end-line"
case CopyRight = "copyright"
}
extension String {
func fixUnknownEntities() -> String {
let replacementMapping:[String:String] = ["&ldblquot;" :"\u{201C}",
"&rdblquot;" :"\u{201D}",
"&lquot;" :"\u{2018}",
"&rquot;" :"\u{2019}",
"&emdash;" :"\u{2014}",
"&endash;" :"\u{2013}",
"&ellipsis;" :"\u{2026}",
"&ellipsis4;":"\u{2026}.", //This one is nasty!
"&emacron;" :"ē"]
return replacementMapping.reduce(self) { acc,tuple in
return acc.replacingOccurrences(of: tuple.key, with: tuple.value)
}
}
}
public class ESVXMLParser: NSObject, XMLParserDelegate {
let parser:XMLParser
var elementStack: [ESVXMLElement] = []
var passage:ESVPassage = ESVPassage()
var currentFootnoteID = ""
public init(withString xmlString: String) {
let hackedXMLString = xmlString.fixUnknownEntities()
let xmlData = hackedXMLString.data(using: String.Encoding.utf8)!
parser = XMLParser(data: xmlData)
super.init()
parser.delegate = self;
}
public init?(fromBundle bundle: Bundle = Bundle.main, withName name: String) {
do {
guard let xmlFile = bundle.path(forResource: name, ofType: XML_FILE_TYPE)
else {
return nil
}
let xmlString = try String(contentsOfFile: xmlFile)
let hackedXMLString = xmlString.fixUnknownEntities()
let xmlData = hackedXMLString.data(using: String.Encoding.utf8)!
parser = XMLParser(data: xmlData)
super.init()
parser.delegate = self;
} catch {
return nil
}
}
public func parse() -> ESVPassage? {
let success = parser.parse()
if success {
return passage
} else {
return nil
}
}
public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
guard let element = ESVXMLElement(rawValue: elementName)
else {
return
}
switch element {
case .BeginChapter:
guard let chapterNumber = Int(attributeDict["num"]!)
else {
parser.abortParsing()
break
}
passage.textElements.append(.BeginChapter(chapterNumber))
case .FootNote:
guard let footNoteID = attributeDict["id"]
else {
parser.abortParsing()
break
}
passage.textElements.append(.FootNoteMarker(footNoteID))
currentFootnoteID = footNoteID
case .BeginBlockIndent:
passage.textElements.append(.BeginBlockIndent)
case .BeginParagraph:
passage.textElements.append(.BeginParagraph)
case .BeginLine:
if let classs = attributeDict["class"] {
let isIndented = classs == "indent"
passage.textElements.append(.BeginLine(indented: isIndented))
} else {
passage.textElements.append(.BeginLine(indented: false))
}
case .EndBlockIndent:
passage.textElements.append(.EndBlockIndent)
case .EndParagraph:
passage.textElements.append(.EndParagraph)
case .EndLine:
passage.textElements.append(.EndLine)
default:
break
}
elementStack.append(element)
}
public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementStack.last == ESVXMLElement(rawValue: elementName) {
if let element = elementStack.popLast() {
switch element {
case .FootNote:
currentFootnoteID = ""
default:
break
}
}
}
}
public func parser(_ parser: XMLParser, foundCharacters string: String) {
if string == NEWLINE {
return
}
if let topElement = elementStack.last {
switch topElement {
case .Reference:
passage.reference = string
case .Heading:
passage.textElements.append(ESVPassageTextElement.Heading(string))
case .VerseNumber:
guard let verseNumber = Int(string)
else {
parser.abortParsing()
break
}
passage.textElements.append(ESVPassageTextElement.VerseNumber(verseNumber))
case .VerseUnit:
passage.textElements.append(ESVPassageTextElement.VerseUnit(string))
case .CopyRight:
passage.copyright = string
case .FootNote:
passage.addFootNote(forID: currentFootnoteID, withBody: string)
case .WordsOfChrist:
passage.textElements.append(ESVPassageTextElement.WordsOfChrist(string))
default:
break
}
}
}
}
| apache-2.0 | ac9326dfd7eeb6093cff8aaa9d8183f4 | 31.927885 | 186 | 0.501387 | 5.036029 | false | false | false | false |
nataliq/TripCheckins | TripCheckins/Checkin List/Trip Service/PredefinedTripService.swift | 1 | 1255 | //
// PredefinedTripService.swift
// TripCheckins
//
// Created by Nataliya on 8/13/17.
// Copyright © 2017 Nataliya Patsovska. All rights reserved.
//
import Foundation
class PredefinedTripService: TripLoadingService {
func loadAllTrips(_ completion:([Trip]) -> Void) {
let now = Date()
var lastWeekComponents = DateComponents()
lastWeekComponents.day = -7
var lastMonthComponents = DateComponents()
lastMonthComponents.month = -1
var lastYearComponents = DateComponents()
lastYearComponents.year = -1
let lastYearOnThisDay = Calendar.current.date(byAdding: lastYearComponents, to: now)!
let trips = [
Trip(startDate: Calendar.current.date(byAdding: lastWeekComponents, to: now)!,
endDate: nil,
name: "Last week"),
Trip(startDate: Calendar.current.date(byAdding: lastMonthComponents, to: now)!,
endDate: nil,
name: "Last month"),
Trip(startDate: lastYearOnThisDay,
endDate: lastYearOnThisDay.addingTimeInterval(24*3600),
name: "This day, 1 year ago")
]
completion(trips)
}
}
| mit | 7f56101fdc2390d3ccaff98504cf6093 | 31.153846 | 93 | 0.598884 | 4.644444 | false | false | false | false |
OHAKO-Inc/OHAKO-Prelude | PreludePlayground.playground/Pages/UIAlertController+ImageSelection.xcplaygroundpage/Contents.swift | 1 | 1701 | //: [Previous](@previous)
/*:
## showImageSelectAlertController(container: UIViewController, imagePicker: UIImagePickerController)
*/
import UIKit
import XCPlayground
import PlaygroundSupport
import Prelude
class ViewController: UIViewController {
lazy var button: UIButton = {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 375, height: 667))
button.setTitle("ImageSelection", for: .normal)
button.setTitleColor(.black, for: .normal)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(button)
button.addTarget(self, action: #selector(ViewController.imageSelectionButtonTapped(_:)), for: .touchUpInside)
}
@objc func imageSelectionButtonTapped(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
UIAlertController.showImageSelectAlertController(container: self, imagePicker: imagePicker)
}
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
guard info[UIImagePickerControllerEditedImage] != nil else {
return
}
// use image
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
let viewController = ViewController()
PlaygroundPage.current.liveView = viewController
//: [Next](@next)
| mit | bb695b41c7d9e6dff947f54651683a5f | 32.352941 | 118 | 0.709583 | 5.382911 | false | false | false | false |
Daniel-Lopez/Cent | Sources/String.swift | 1 | 6929 | //
// String.swift
// Cent
//
// Created by Ankur Patel on 6/30/14.
// Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved.
//
import Foundation
import Dollar
public extension String {
public var length: Int {
get {
return self.characters.count
}
}
public var camelCase: String {
get {
return self.deburr().words().reduceWithIndex("") { (result, index, word) -> String in
let lowered = word.lowercaseString
return result + (index > 0 ? lowered.capitalizedString : lowered)
}
}
}
public var kebabCase: String {
get {
return self.deburr().words().reduceWithIndex("", combine: { (result, index, word) -> String in
return result + (index > 0 ? "-" : "") + word.lowercaseString
})
}
}
public var snakeCase: String {
get {
return self.deburr().words().reduceWithIndex("", combine: { (result, index, word) -> String in
return result + (index > 0 ? "_" : "") + word.lowercaseString
})
}
}
public var startCase: String {
get {
return self.deburr().words().reduceWithIndex("", combine: { (result, index, word) -> String in
return result + (index > 0 ? " " : "") + word.capitalizedString
})
}
}
/// Get character at a subscript
///
/// :param i Index for which the character is returned
/// :return Character at index i
public subscript(i: Int) -> Character? {
if let char = Array(self.characters).get(i) {
return char
}
return .None
}
/// Get character at a subscript
///
/// :param i Index for which the character is returned
/// :return Character at index i
public subscript(pattern: String) -> String? {
if let range = Regex(pattern).rangeOfFirstMatch(self).toRange() {
return self[range]
}
return .None
}
/// Get substring using subscript notation and by passing a range
///
/// :param range The range from which to start and end the substring
/// :return Substring
public subscript(range: Range<Int>) -> String {
let start = startIndex.advancedBy(range.startIndex)
let end = startIndex.advancedBy(range.endIndex)
return self.substringWithRange(start..<end)
}
/// Get the start index of Character
///
/// :return start index of .None if not found
public func indexOf(char: Character) -> Int? {
return self.indexOf(char.description)
}
/// Get the start index of string
///
/// :return start index of .None if not found
public func indexOf(str: String) -> Int? {
return self.indexOfRegex(Regex.escapeStr(str))
}
/// Get the start index of regex pattern
///
/// :return start index of .None if not found
public func indexOfRegex(pattern: String) -> Int? {
if let range = Regex(pattern).rangeOfFirstMatch(self).toRange() {
return range.startIndex
}
return .None
}
/// Get an array from string split using the delimiter character
///
/// :return Array of strings after spliting
public func split(delimiter: Character) -> [String] {
return self.componentsSeparatedByString(String(delimiter))
}
/// Remove leading whitespace characters
///
/// :return String without leading whitespace
public func lstrip() -> String {
return self["[^\\s]+.*$"]!
}
/// Remove trailing whitespace characters
///
/// :return String without trailing whitespace
public func rstrip() -> String {
return self["^.*[^\\s]+"]!
}
/// Remove leading and trailing whitespace characters
///
/// :return String without leading or trailing whitespace
public func strip() -> String {
return self.stringByTrimmingCharactersInSet(.whitespaceCharacterSet())
}
/// Split string into array of 'words'
func words() -> [String] {
let hasComplexWordRegex = try! NSRegularExpression(pattern: RegexHelper.hasComplexWord, options: [])
let wordRange = NSMakeRange(0, self.characters.count)
let hasComplexWord = hasComplexWordRegex.rangeOfFirstMatchInString(self, options: [], range: wordRange)
let wordPattern = hasComplexWord.length > 0 ? RegexHelper.complexWord : RegexHelper.basicWord
let wordRegex = try! NSRegularExpression(pattern: wordPattern, options: [])
let matches = wordRegex.matchesInString(self, options: [], range: wordRange)
let words = matches.map { (result: NSTextCheckingResult) -> String in
if let range = self.rangeFromNSRange(result.range) {
return self.substringWithRange(range)
} else {
return ""
}
}
return words
}
/// Strip string of accents and diacritics
func deburr() -> String {
let mutString = NSMutableString(string: self)
CFStringTransform(mutString, nil, kCFStringTransformStripCombiningMarks, false)
return mutString as String
}
/// Converts an NSRange to a Swift friendly Range supporting Unicode
///
/// :param nsRange the NSRange to be converted
/// :return A corresponding Range if possible
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex)
let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
if let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
} else {
return nil
}
}
}
public extension Character {
/// Get int representation of character
///
/// :return UInt32 that represents the given character
public var ord: UInt32 {
get {
let desc = self.description
return desc.unicodeScalars[desc.unicodeScalars.startIndex].value
}
}
/// Convert character to string
///
/// :return String representation of character
public var description: String {
get {
return String(self)
}
}
}
infix operator =~ {}
/// Regex match the string on the left with the string pattern on the right
///
/// :return true if string matches the pattern otherwise false
public func =~(str: String, pattern: String) -> Bool {
return Regex(pattern).test(str)
}
/// Concat the string to itself n times
///
/// :return concatenated string
public func * (str: String, n: Int) -> String {
var stringBuilder = [String]()
n.times {
stringBuilder.append(str)
}
return stringBuilder.joinWithSeparator("")
}
| mit | 955a4d701165f657883df8ba425b7bf6 | 30.495455 | 111 | 0.60254 | 4.644102 | false | false | false | false |
pixlwave/Stingtk-iOS | Source/Models/Show.swift | 1 | 3047 | import UIKit
class Show: UIDocument {
static var defaultName = "Show"
override var fileType: String { return "uk.pixlwave.stingpad.show" }
var fileExists: Bool { return FileManager.default.fileExists(atPath: fileURL.path) }
var fileName: String { return fileURL.deletingPathExtension().lastPathComponent }
private(set) var stings = [Sting]() {
didSet { NotificationCenter.default.post(Notification(name: .stingsDidChange, object: self)) }
}
var unavailableStings: [Sting] { stings.filter { $0.availability != .available } }
enum DocumentError: Error {
case invalidData
}
convenience init(name: String?) {
let fileName: String
if let name = name, !name.isEmpty {
fileName = name
} else {
fileName = Show.defaultName
}
let url = FileManager.default.temporaryDirectory.appendingPathComponent("\(fileName).stings")
self.init(fileURL: url)
}
override func load(fromContents contents: Any, ofType typeName: String?) throws {
guard let data = contents as? Data else { throw DocumentError.invalidData }
FolderBookmarks.shared.startAccessingSecurityScopedResources()
defer { FolderBookmarks.shared.stopAccessingSecurityScopedResources() }
let stings = try JSONDecoder().decode([Sting].self, from: data)
self.stings = stings
}
override func contents(forType typeName: String) throws -> Any {
let jsonData = try JSONEncoder().encode(stings)
return jsonData
}
func reloadUnavailableStings() {
FolderBookmarks.shared.startAccessingSecurityScopedResources()
defer { FolderBookmarks.shared.stopAccessingSecurityScopedResources() }
unavailableStings.filter { $0.availability != .available }.forEach { sting in
sting.reloadAudioWithBookmarks()
}
}
// editing functions exist to allow the show to load without updating it's change count
func append(_ sting: Sting) {
stings.append(sting)
undoManager.registerUndo(withTarget: self) { _ in
self.removeSting(at: self.stings.count - 1)
}
}
func insert(_ sting: Sting, at index: Int) {
stings.insert(sting, at: index)
undoManager.registerUndo(withTarget: self) { _ in
self.removeSting(at: index)
}
}
func moveSting(from sourceIndex: Int, to destinationIndex: Int) {
stings.insert(stings.remove(at: sourceIndex), at: destinationIndex)
undoManager.registerUndo(withTarget: self) { _ in
self.moveSting(from: destinationIndex, to: sourceIndex)
}
}
@discardableResult
func removeSting(at index: Int) -> Sting {
let sting = stings.remove(at: index)
undoManager.registerUndo(withTarget: self) { _ in
self.insert(sting, at: index)
}
return sting
}
}
| mpl-2.0 | a70e07ece7d65bb6fa393ab632e0c8a9 | 32.483516 | 102 | 0.628159 | 4.651908 | false | false | false | false |
GianniCarlo/Audiobook-Player | Shared/Models/LibraryItem+CoreDataClass.swift | 1 | 2112 | //
// LibraryItem+CoreDataClass.swift
// BookPlayerKit
//
// Created by Gianni Carlo on 4/23/19.
// Copyright © 2019 Tortuga Power. All rights reserved.
//
//
import CoreData
import Foundation
import UIKit
@objc(LibraryItem)
public class LibraryItem: NSManagedObject, Codable {
public var fileURL: URL? {
guard self.relativePath != nil else { return nil }
return DataManager.getProcessedFolderURL().appendingPathComponent(self.relativePath)
}
var cachedArtwork: UIImage?
public func getLibrary() -> Library? {
if let parentFolder = self.folder {
return parentFolder.getLibrary()
}
return self.library
}
public func getBookToPlay() -> Book? {
return nil
}
// Represents sum of current time
public var progress: Double {
return 0
}
// Percentage represented from 0 to 1
public var progressPercentage: Double {
return 1.0
}
public func getArtwork(for theme: Theme?) -> UIImage? {
if let cachedArtwork = self.cachedArtwork {
return cachedArtwork
}
guard let artworkData = self.artworkData,
let image = UIImage(data: artworkData as Data) else {
#if os(iOS)
self.cachedArtwork = DefaultArtworkFactory.generateArtwork(from: theme?.linkColor)
#endif
return self.cachedArtwork
}
self.cachedArtwork = image
return image
}
public func info() -> String { return "" }
public func jumpToStart() {}
public func markAsFinished(_ flag: Bool) {}
public func setCurrentTime(_ time: Double) {}
public func index(for item: LibraryItem) -> Int? { return nil }
public func getItem(with relativePath: String) -> LibraryItem? { return nil }
public func encode(to encoder: Encoder) throws {
fatalError("LibraryItem is an abstract class, override this function in the subclass")
}
public required convenience init(from decoder: Decoder) throws {
fatalError("LibraryItem is an abstract class, override this function in the subclass")
}
}
| gpl-3.0 | 3cd25d5a91d85408c0e9bc464e22a8b5 | 24.433735 | 94 | 0.655613 | 4.68071 | false | false | false | false |
akane/Akane | Akane/Akane/Collection/Layout/TableViewFlowLayout.swift | 1 | 1661 | //
// This file is part of Akane
//
// Created by JC on 19/01/16.
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code
//
import Foundation
/**
AutoLayout support for `UITableView`
*/
open class TableViewFlowLayout : NSObject, TableViewLayout {
public typealias Height = (estimated: CGFloat?, actual: CGFloat)
let rowHeight: Height?
let footerHeight: Height?
let headerHeight: Height?
public init(rowHeight: Height? = nil, headerHeight: Height? = nil, footerHeight: Height? = nil) {
self.rowHeight = rowHeight
self.headerHeight = headerHeight
self.footerHeight = footerHeight
}
open func heightForCell(_ indexPath: IndexPath) -> CGFloat? {
return self.rowHeight?.actual
}
open func estimatedHeightForCell(_ indexPath: IndexPath) -> CGFloat? {
return self.rowHeight?.estimated
}
open func heightForSection(_ section: Int, sectionKind: String) -> CGFloat? {
switch(sectionKind) {
case "header":
return self.headerHeight?.actual
case "footer":
return self.footerHeight?.actual
default:
return nil
}
}
open func estimatedHeightForSection(_ section: Int, sectionKind: String) -> CGFloat? {
switch(sectionKind) {
case "header":
return self.headerHeight?.estimated
case "footer":
return self.footerHeight?.estimated
default:
return 0
}
}
open func didReuseView(_ reusableView: UIView) {
reusableView.layoutIfNeeded()
}
}
| mit | 338b28c1e95b16960dc6d82d5f748c26 | 26.683333 | 101 | 0.638772 | 4.800578 | false | false | false | false |
4taras4/giphyVIP | VIPTemplate/Other/Extensions.swift | 1 | 5656 | //
// Extensions.swift
// VIPTemplate
//
// Created by Taras Markevych on 19.10.17.
// Copyright © 2017 Taras Markevych. All rights reserved.
//
import UIKit
import ImageIO
import UIKit
import ImageIO
extension UIImage {
public class func gifImageWithData(data: NSData) -> UIImage? {
guard let source = CGImageSourceCreateWithData(data, nil) else {
print("image doesn't exist")
return nil
}
return UIImage.animatedImageWithSource(source: source)
}
public class func gifImageWithURL(gifUrl:String) -> UIImage? {
guard let bundleURL = NSURL(string: gifUrl)
else {
print("image named \"\(gifUrl)\" doesn't exist")
return nil
}
guard let imageData = NSData(contentsOf: bundleURL as URL) else {
print("image named \"\(gifUrl)\" into NSData")
return nil
}
return gifImageWithData(data: imageData)
}
public class func gifImageWithName(name: String) -> UIImage? {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let bundleURL = URL(fileURLWithPath: documentsPath!).appendingPathComponent("\(name).gif")
guard let imageData = NSData(contentsOf: bundleURL) else {
print("SwiftGif: Cannot turn image named \"\(name)\" into NSData")
return nil
}
return gifImageWithData(data: imageData)
}
class func delayForImageAtIndex(index: Int, source: CGImageSource!) -> Double {
var delay = 0.1
let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
let gifProperties: CFDictionary = unsafeBitCast(CFDictionaryGetValue(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque()), to: CFDictionary.self)
var delayObject: AnyObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()), to: AnyObject.self)
if delayObject.doubleValue == 0 {
delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self)
}
delay = delayObject as! Double
if delay < 0.1 {
delay = 0.1
}
return delay
}
class func gcdForPair(a: Int?, _ b: Int?) -> Int {
var a = a
var b = b
if b == nil || a == nil {
if b != nil {
return b!
} else if a != nil {
return a!
} else {
return 0
}
}
if a! < b! {
let c = a!
a = b!
b = c
}
var rest: Int
while true {
rest = a! % b!
if rest == 0 {
return b!
} else {
a = b!
b = rest
}
}
}
class func gcdForArray(array: Array<Int>) -> Int {
if array.isEmpty {
return 1
}
var gcd = array[0]
for val in array {
gcd = UIImage.gcdForPair(a: val, gcd)
}
return gcd
}
class func animatedImageWithSource(source: CGImageSource) -> UIImage? {
let count = CGImageSourceGetCount(source)
var images = [CGImage]()
var delays = [Int]()
for i in 0..<count {
if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
images.append(image)
}
let delaySeconds = UIImage.delayForImageAtIndex(index: Int(i), source: source)
delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms
}
let duration: Int = {
var sum = 0
for val: Int in delays {
sum += val
}
return sum
}()
let gcd = gcdForArray(array: delays)
var frames = [UIImage]()
var frame: UIImage
var frameCount: Int
for i in 0..<count {
frame = UIImage(cgImage: images[Int(i)])
frameCount = Int(delays[Int(i)] / gcd)
for _ in 0..<frameCount {
frames.append(frame)
}
}
let animation = UIImage.animatedImage(with: frames, duration: Double(duration) / 1000.0)
return animation
}
}
extension UIImageView {
func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() { () -> Void in
self.image = image
}
}.resume()
}
public func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleToFill) {
guard let url = URL(string: link) else { return }
downloadedFrom(url: url, contentMode: mode)
}
}
| gpl-3.0 | ac87309a384787eb831cca344f1847dc | 29.079787 | 183 | 0.531742 | 5.164384 | false | false | false | false |
Mayfleet/SimpleChat | Frontend/iOS/SimpleChat/SimpleChat/AppDelegate.swift | 1 | 1847 | //
// AppDelegate.swift
// SimpleChat
//
// Created by Maxim Pervushin on 01/03/16.
// Copyright © 2016 Maxim Pervushin. All rights reserved.
//
import UIKit
import JSQMessagesViewController
import CocoaLumberjack
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let chatDispatcher = ChatDispatcher()
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject:AnyObject]?) -> Bool {
initLogger()
initAppearance()
return true
}
private func initAppearance() {
UIView.appearance().tintColor = UIColor.flatBlackColor()
UINavigationBar.appearance().barStyle = .Black
UINavigationBar.appearance().barTintColor = UIColor.flatPurpleColor()
UINavigationBar.appearance().tintColor = UIColor.flatWhiteColor()
JSQMessagesInputToolbar.appearance().barStyle = .Black
JSQMessagesInputToolbar.appearance().barTintColor = UIColor.flatPurpleColor()
JSQMessagesInputToolbar.appearance().tintColor = UIColor.flatWhiteColor()
UIButton.appearanceWhenContainedInInstancesOfClasses([JSQMessagesInputToolbar.self]).tintColor = UIColor.flatWhiteColor()
UIButton.appearanceWhenContainedInInstancesOfClasses([JSQMessagesInputToolbar.self]).setTitleColor(UIColor.flatWhiteColor(), forState: .Normal)
UIButton.appearanceWhenContainedInInstancesOfClasses([JSQMessagesInputToolbar.self]).setTitleColor(UIColor.flatWhiteColor(), forState: .Highlighted)
BackgroundTableView.appearance().backgroundColor = UIColor.flatPurpleColorDark()
BackgroundView.appearance().backgroundColor = UIColor.flatPurpleColorDark()
}
private func initLogger() {
DDLog.addLogger(DDTTYLogger.sharedInstance()) // TTY = Xcode console
}
}
| mit | aa7bd68f70ae1140c90db18fccdcc2ef | 36.673469 | 156 | 0.751354 | 5.786834 | false | false | false | false |
red-spotted-newts-2014/Im-In | im-in-ios/im-in-ios/untitled folder/APIAddEventController.swift | 1 | 3299 | //
// APIController.swift
//
// Created by fahia mohamed on 2014-08-14.
// Copyright (c) 2014 fahia mohamed. All rights reserved.
//
import Foundation
protocol APIAddEventControllerProtocol {
func didReceiveAPIResults(results: AnyObject!)
}
class APIAddEventController {
var delegate: APIAddEventControllerProtocol?
var param: NSDictionary?
init() {
}
func sendCreateEventInfo(info: NSDictionary) {
var request = NSMutableURLRequest(URL: NSURL(string: "http://10.0.2.26:3000/events"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var params = ["name": info.objectForKey("name"),"description": info.objectForKey("description"), "start_time": info.objectForKey("start_time"), "end_time": info.objectForKey("end_time"), "venue": info.objectForKey("venue"), "location": info.objectForKey("location")] as Dictionary
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as AnyObject!
// if(err) {
// println(err!.localizedDescription)
// }
// else {
// var success = json["success"] as? Int
// println("Succes: \(success)")
// }
self.delegate?.didReceiveAPIResults(json)
})
task.resume()
}
func sendInviteInfo(users: NSMutableArray, params: NSDictionary) {
println("at the api")
// println(users)
// println(params)
var param = ["event":params, "users":users]
println("******")
println(param)
var request = NSMutableURLRequest(URL: NSURL(string: "http://10.0.2.26:3000/events/create_ios"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
// var params = ["name": info.objectForKey("name"),"description": info.objectForKey("description"), "start_time": info.objectForKey("start_time"), "end_time": info.objectForKey("end_time"), "venue": info.objectForKey("venue"), "location": info.objectForKey("location")] as Dictionary
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(param, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("\(countElements(param))", forHTTPHeaderField: "Content-Length")
var connection = NSURLConnection(request: request, delegate: self, startImmediately: false)
connection.start()
println("Sending request")
}
} | mit | c8eb85fb849efa2734c8173a128ae57f | 40.772152 | 290 | 0.63595 | 4.666195 | false | false | false | false |
cxy921126/SoftSwift | SoftSwift/SoftSwift/HomeViewController.swift | 1 | 8504 | //
// HomeViewController.swift
// SoftSwift
//
// Created by Mac mini on 16/3/3.
// Copyright © 2016年 XMU. All rights reserved.
//
import UIKit
import SDWebImage
import MBProgressHUD
class HomeViewController: BaseViewController, ListViewDelegate{
let screenWidth = UIScreen.mainScreen().bounds.width
let screenHeight = UIScreen.mainScreen().bounds.height
let userAccount = UserAccount.readAccount()
let cellReuseIdentifier = "cell"
var statuses = [Status](){
didSet{
tableView.reloadData()
}
}
///是否加载新微博的标识(反之加载旧微博)
var isLoadingNew = true
override func viewDidLoad() {
super.viewDidLoad()
if !isLogin
{
return
}
//为tableview注册cell
tableView.registerNib(UINib(nibName: "HomeTableViewCell", bundle: nil), forCellReuseIdentifier: cellReuseIdentifier)
//高度自适应
tableView.estimatedRowHeight = 300
tableView.rowHeight = UITableViewAutomaticDimension
setNaviBar()
list.listDelegate = self
//首次加载数据
loadData()
//下拉刷新
refreshControl = statusRefreshControl
refreshControl?.addTarget(self, action: #selector(loadData), forControlEvents: .ValueChanged)
//刷新数量提醒
navigationController?.view.insertSubview(hintLabel, atIndex: 1)
hintLabel.hidden = true
}
//MARK: - 加载微博数据
var since_id = 0
var max_id = 0
///微博加载数量
var newStatusesCount : Int = 0{
didSet{
//显示微博加载数量的动画
hintLabel.hidden = false
UIView.animateWithDuration(1.0, animations: {
self.hintLabel.transform = CGAffineTransformMakeTranslation(0, 64)
self.hintLabel.text = "\(self.newStatusesCount) Weibo Loaded."
}) { (_) in
UIView.animateWithDuration(1.5, animations: {
self.hintLabel.transform = CGAffineTransformIdentity
}, completion: { (_) in
self.hintLabel.hidden = true
})
}
}
}
///微博加载数量标签
lazy var hintLabel:UILabel = {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 44))
label.backgroundColor = UIColor.orangeColor()
label.textAlignment = .Center
label.textColor = UIColor.whiteColor()
label.alpha = 0.9
return label
}()
func loadData(){
//如果isLoadingNew为真则加载新微博,否则加载旧微博
if isLoadingNew==true{
if since_id == 0 {
MBProgressHUD.showHUDAddedTo(view, animated: true)
}
//加载statuses
Status.loadStatuses(since_id, max_id: 0) { (models) -> () in
self.statuses = models + self.statuses
self.since_id = (self.statuses.first?.id)!
self.max_id = (self.statuses.last?.id)!
self.refreshControl?.endRefreshing()
self.newStatusesCount = models.count
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
}
else{
Status.loadStatuses(0, max_id: max_id, finished: { (models) in
self.statuses = self.statuses + models
self.since_id = (self.statuses.first?.id)!
self.max_id = (self.statuses.last?.id)!
})
}
}
//MARK: - 下拉刷新控件
lazy var statusRefreshControl: StatusRefreshControl = {
let refreshControl = NSBundle.mainBundle().loadNibNamed("StatusRefreshControl", owner: self, options: nil).first as! StatusRefreshControl
if refreshControl.refreshing == true{
self.isLoadingNew = true
}
return refreshControl
}()
//MARK: - 设置昵称按钮和导航条
lazy var nameBtn:nameButton = {
let nameBtn = nameButton()
//请求获得账户昵称
let access_token = UserAccount.readAccount()!.access_token
let uid = UserAccount.readAccount()!.uid
let params = ["access_token" : access_token, "uid" : uid]
NetworkTool.sharedNetworkTool().GET("2/users/show.json", parameters: params, progress: nil, success: { (_, JSON) in
let dic = JSON as! [String : AnyObject]
nameBtn.setTitle(dic["screen_name"] as? String, forState: UIControlState.Normal)
}
, failure: { (_, err) in
print(err)
})
nameBtn.addTarget(self, action: #selector(HomeViewController.nameBtnClick), forControlEvents: UIControlEvents.TouchUpInside)
return nameBtn
}()
func setNaviBar(){
let leftBtn = UIButton()
leftBtn.setImage(UIImage(named: "navigationbar_friendattention"), forState: UIControlState.Normal)
leftBtn.setImage(UIImage(named: "navigationbar_friendattention_highlighted"), forState: UIControlState.Highlighted)
leftBtn.sizeToFit()
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn)
let rightBtn = UIButton()
rightBtn.setImage(UIImage(named: "navigationbar_pop"), forState: UIControlState.Normal)
rightBtn.setImage(UIImage(named: "navigationbar_pop_highlighted"), forState: UIControlState.Highlighted)
rightBtn.sizeToFit()
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
nameBtn.sizeToFit()
navigationItem.titleView = nameBtn
}
//MARK: - 设置listView
lazy var list:ListView = {
let list = NSBundle.mainBundle().loadNibNamed("ListView", owner: self, options: nil).last as! ListView
list.frame = CGRect(x:0, y: 0, width: self.screenWidth, height: self.screenHeight)
list.backgroundColor = UIColor(white: 0.0, alpha: 0.3)
return list
}()
//MARK: - 弹出菜单
func nameBtnClick(){
if nameBtn.selected == false{
//view.addSubview(list)
navigationController?.view.addSubview(list)
nameBtn.selected = true
}
else{
list.removeFromSuperview()
nameBtn.selected = false
}
}
//MARK: - 实现listView移除的代理方法
func listViewDidRemove(list: ListView) {
nameBtn.selected = false
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
list.removeFromSuperview()
}
//MARK: - 设置未登录页面
override func setUnloginView() {
super.setUnloginView()
unloginView.titleImage.image = UIImage(named: "visitordiscover_feed_image_house")
unloginView.descriptionLabel.text = "Follow people to find something interesting."
unloginView.titleImageTopMargin.constant = 175
unloginView.titleImageBottomMargin.constant = 50
let animate = CABasicAnimation(keyPath: "transform.rotation")
animate.toValue = 2 * M_PI
animate.speed = 2
animate.duration = 20
animate.repeatCount = MAXFLOAT
animate.removedOnCompletion = false
unloginView.rotateImage.layer.addAnimation(animate, forKey: nil)
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return statuses.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier, forIndexPath: indexPath) as! HomeTableViewCell
let status = statuses[indexPath.row]
cell.status = status
//判断滚动到最后一条时,加载之前的微博
if indexPath.row == statuses.count-1{
isLoadingNew = false
loadData()
}
//第一条时将isloadingnew标记改为true
if indexPath.row == 0 {
isLoadingNew = true
}
return cell
}
}
| mit | b73891b8bbe174b7d878114def47e0d0 | 33.045833 | 145 | 0.600538 | 4.946126 | false | false | false | false |
kriscarle/dev4outdoors-parkbook | Parkbook/BeaconManager.swift | 1 | 3753 | //
// BeaconManager.swift
// RegionMonitoringSwift
//
// Created by Nicolas Flacco on 6/25/14.
// Copyright (c) 2014 Nicolas Flacco. All rights reserved.
//
import CoreLocation
import UIKit
// General search criteria for beacons that are broadcasting
let BEACON_PROXIMITY_UUID = NSUUID(UUIDString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D")
// Beacons are hardcoded into our app so we can easily filter for them in a noisy environment
//let BEACON_PURPLE_MAJOR: CLBeaconMajorValue = 15071
//let BEACON_PURPLE_MINOR: CLBeaconMinorValue = 10507
let BEACON_GREEN_MAJOR: CLBeaconMajorValue = 41057
let BEACON_GREEN_MINOR: CLBeaconMinorValue = 9738
protocol BeaconManagerDelegate {
func insideRegion(regionIdentifier: String)
func didEnterRegion(regionIdentifier: String)
func didExitRegion(regionIdentifier: String)
}
class BeaconManager: NSObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager = CLLocationManager()
let registeredBeaconMajor = [BEACON_GREEN_MAJOR]
let greenRegion: CLBeaconRegion = CLBeaconRegion(proximityUUID:BEACON_PROXIMITY_UUID, major: BEACON_GREEN_MAJOR, identifier:"National Mall")
//let purpleRegion: CLBeaconRegion = CLBeaconRegion(proximityUUID: BEACON_PROXIMITY_UUID, major: BEACON_PURPLE_MAJOR, identifier: "purple")
var delegate: BeaconManagerDelegate?
class var sharedInstance:BeaconManager {
return sharedBeaconManager
}
override init() {
super.init()
locationManager.delegate = self
}
func start() {
println("BM start");
if CLLocationManager.authorizationStatus() == .NotDetermined {
locationManager.requestAlwaysAuthorization()
}
//clear current regions
//for locationManager.monitoredRegions
locationManager.startMonitoringForRegion(greenRegion)
//locationManager.startMonitoringForRegion(purpleRegion)
}
func stop() {
println("BM stop");
locationManager.stopMonitoringForRegion(greenRegion)
//locationManager.stopMonitoringForRegion(purpleRegion)
}
// CLLocationManagerDelegate methods
func locationManager(manager: CLLocationManager!, didStartMonitoringForRegion region: CLRegion!) {
println("BM didStartMonitoringForRegion")
locationManager.requestStateForRegion(region) // should locationManager be manager?
}
func locationManager(manager: CLLocationManager, didEnterRegion:CLRegion) {
println("BM didEnterRegion \(didEnterRegion.identifier)")
delegate?.didEnterRegion(didEnterRegion.identifier)
}
func locationManager(manager: CLLocationManager, didExitRegion:CLRegion) {
println("BM didExitRegion \(didExitRegion.identifier)")
delegate?.didExitRegion(didExitRegion.identifier)
}
func locationManager(manager: CLLocationManager!, didDetermineState state: CLRegionState, forRegion region: CLRegion!) {
println("BM didDetermineState \(state)");
switch state {
case .Inside:
println("BeaconManager:didDetermineState CLRegionState.Inside \(region.identifier)");
delegate?.insideRegion(region.identifier)
case .Outside:
println("BeaconManager:didDetermineState CLRegionState.Outside");
case .Unknown:
println("BeaconManager:didDetermineState CLRegionState.Unknown");
default:
println("BeaconManager:didDetermineState default");
}
}
func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) {
}
}
let sharedBeaconManager = BeaconManager() | mit | e9c37388ac30e78fb2dcdc38a84fab9e | 35.096154 | 144 | 0.711964 | 5.141096 | false | false | false | false |
manavgabhawala/swift | test/DebugInfo/returnlocation.swift | 4 | 6242 | // RUN: %target-swift-frontend -g -emit-ir %s -o %t.ll
// REQUIRES: objc_interop
import Foundation
// This file contains linetable testcases for all permutations
// of simple/complex/empty return expressions,
// cleanups/no cleanups, single / multiple return locations.
// RUN: %FileCheck %s --check-prefix=CHECK_NONE < %t.ll
// CHECK_NONE: define{{( protected)?}} {{.*}}void {{.*}}none
public func none(_ a: inout Int64) {
// CHECK_NONE: call void @llvm.dbg{{.*}}, !dbg
// CHECK_NONE: !dbg ![[NONE_INIT:.*]]
a -= 2
// CHECK_NONE: ret {{.*}}, !dbg ![[NONE_RET:.*]]
// CHECK_NONE: ![[NONE_INIT]] = !DILocation(line: [[@LINE-2]], column:
// CHECK_NONE: ![[NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_EMPTY < %t.ll
// CHECK_EMPTY: define {{.*}}empty
public func empty(_ a: inout Int64) {
if a > 24 {
// CHECK-DAG_EMPTY: br {{.*}}, !dbg ![[EMPTY_RET1:.*]]
// CHECK-DAG_EMPTY_RET1: ![[EMPTY_RET1]] = !DILocation(line: [[@LINE+1]], column: 6,
return
}
a -= 2
// CHECK-DAG_EMPTY: br {{.*}}, !dbg ![[EMPTY_RET2:.*]]
// CHECK-DAG_EMPTY_RET2: ![[EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 3,
return
// CHECK-DAG_EMPTY: ret {{.*}}, !dbg ![[EMPTY_RET:.*]]
// CHECK-DAG_EMPTY: ![[EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_EMPTY_NONE < %t.ll
// CHECK_EMPTY_NONE: define {{.*}}empty_none
public func empty_none(_ a: inout Int64) {
if a > 24 {
return
}
a -= 2
// CHECK_EMPTY_NONE: ret {{.*}}, !dbg ![[EMPTY_NONE_RET:.*]]
// CHECK_EMPTY_NONE: ![[EMPTY_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_SIMPLE_RET < %t.ll
// CHECK_SIMPLE_RET: define {{.*}}simple
public func simple(_ a: Int64) -> Int64 {
if a > 24 {
return 0
}
return 1
// CHECK_SIMPLE_RET: ret i{{.*}}, !dbg ![[SIMPLE_RET:.*]]
// CHECK_SIMPLE_RET: ![[SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_COMPLEX_RET < %t.ll
// CHECK_COMPLEX_RET: define {{.*}}complex
public func complex(_ a: Int64) -> Int64 {
if a > 24 {
return a*a
}
return a/2
// CHECK_COMPLEX_RET: ret i{{.*}}, !dbg ![[COMPLEX_RET:.*]]
// CHECK_COMPLEX_RET: ![[COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_COMPLEX_SIMPLE < %t.ll
// CHECK_COMPLEX_SIMPLE: define {{.*}}complex_simple
public func complex_simple(_ a: Int64) -> Int64 {
if a > 24 {
return a*a
}
return 2
// CHECK_COMPLEX_SIMPLE: ret i{{.*}}, !dbg ![[COMPLEX_SIMPLE_RET:.*]]
// CHECK_COMPLEX_SIMPLE: ![[COMPLEX_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_SIMPLE_COMPLEX < %t.ll
// CHECK_SIMPLE_COMPLEX: define {{.*}}simple_complex
public func simple_complex(_ a: Int64) -> Int64 {
if a > 24 {
return a*a
}
return 2
// CHECK_SIMPLE_COMPLEX: ret {{.*}}, !dbg ![[SIMPLE_COMPLEX_RET:.*]]
// CHECK_SIMPLE_COMPLEX: ![[SIMPLE_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// ---------------------------------------------------------------------
// RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_NONE < %t.ll
// CHECK_CLEANUP_NONE: define {{.*}}cleanup_none
public func cleanup_none(_ a: inout NSString) {
a = "empty"
// CHECK_CLEANUP_NONE: ret void, !dbg ![[CLEANUP_NONE_RET:.*]]
// CHECK_CLEANUP_NONE: ![[CLEANUP_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_EMPTY < %t.ll
// CHECK_CLEANUP_EMPTY: define {{.*}}cleanup_empty
public func cleanup_empty(_ a: inout NSString) {
if a.length > 24 {
return
}
a = "empty"
return
// CHECK_CLEANUP_EMPTY: ret void, !dbg ![[CLEANUP_EMPTY_RET:.*]]
// CHECK_CLEANUP_EMPTY: ![[CLEANUP_EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_EMPTY_NONE < %t.ll
// CHECK_CLEANUP_EMPTY_NONE: define {{.*}}cleanup_empty_none
public func cleanup_empty_none(_ a: inout NSString) {
if a.length > 24 {
return
}
a = "empty"
// CHECK_CLEANUP_EMPTY_NONE: ret {{.*}}, !dbg ![[CLEANUP_EMPTY_NONE_RET:.*]]
// CHECK_CLEANUP_EMPTY_NONE: ![[CLEANUP_EMPTY_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_SIMPLE_RET < %t.ll
// CHECK_CLEANUP_SIMPLE_RET: define {{.*}}cleanup_simple
public func cleanup_simple(_ a: NSString) -> Int64 {
if a.length > 24 {
return 0
}
return 1
// CHECK_CLEANUP_SIMPLE_RET: ret {{.*}}, !dbg ![[CLEANUP_SIMPLE_RET:.*]]
// CHECK_CLEANUP_SIMPLE_RET: ![[CLEANUP_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_COMPLEX < %t.ll
// CHECK_CLEANUP_COMPLEX: define {{.*}}cleanup_complex
public func cleanup_complex(_ a: NSString) -> Int64 {
if a.length > 24 {
return Int64(a.length*a.length)
}
return Int64(a.length/2)
// CHECK_CLEANUP_COMPLEX: ret i{{.*}}, !dbg ![[CLEANUP_COMPLEX_RET:.*]]
// CHECK_CLEANUP_COMPLEX: ![[CLEANUP_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_COMPLEX_SIMPLE < %t.ll
// CHECK_CLEANUP_COMPLEX_SIMPLE: define {{.*}}cleanup_complex_simple
public func cleanup_complex_simple(_ a: NSString) -> Int64 {
if a.length > 24 {
return Int64(a.length*a.length)
}
return 2
// CHECK_CLEANUP_COMPLEX_SIMPLE: ret {{.*}}, !dbg ![[CLEANUP_COMPLEX_SIMPLE_RET:.*]]
// CHECK_CLEANUP_COMPLEX_SIMPLE: ![[CLEANUP_COMPLEX_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_SIMPLE_COMPLEX < %t.ll
// CHECK_CLEANUP_SIMPLE_COMPLEX: define {{.*}}cleanup_simple_complex
public func cleanup_simple_complex(_ a: NSString) -> Int64 {
if a.length > 24 {
return Int64(a.length*a.length)
}
return 2
// CHECK_CLEANUP_SIMPLE_COMPLEX: ret {{.*}}, !dbg ![[CLEANUP_SIMPLE_COMPLEX_RET:.*]]
// CHECK_CLEANUP_SIMPLE_COMPLEX: ![[CLEANUP_SIMPLE_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// ---------------------------------------------------------------------
| apache-2.0 | b3d74cf84c05cd0f91d6e0bcf5f95568 | 33.871508 | 110 | 0.600609 | 3.152525 | false | false | false | false |
arkverse/SwiftRecord | Example-iOS/SwiftRecordExample/SwiftRecordExample/AppDelegate.swift | 1 | 6157 | //
// AppDelegate.swift
// SwiftRecordExample
//
// Created by Zaid on 5/8/15.
// Copyright (c) 2015 ark. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.ark.SwiftRecordExample" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("SwiftRecordExample", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
var coordinator: NSPersistentStoreCoordinator?
do {
// Create the coordinator and store
coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SwiftRecordExample.sqlite")
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch let error as NSError {
coordinator = nil
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error.userInfo)")
abort()
} catch {
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data."
var error = NSError(domain: "Initialization", code: 0, userInfo: dict)
NSLog("Unresolved error \(error), \(error.userInfo)")
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
if moc.hasChanges {
do {
try moc.save()
} catch let error as NSError {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
}
}
| mit | 3e83ab79d31cbf7eba4dddce1f05f8bc | 50.739496 | 290 | 0.70164 | 5.886233 | false | false | false | false |
nfls/nflsers | app/v2/Controller/Vote/VoteController.swift | 1 | 2067 | //
// VoteController.swift
// NFLSers-iOS
//
// Created by Qingyang Hu on 2018/9/2.
// Copyright © 2018 胡清阳. All rights reserved.
//
import Foundation
import MarkdownView
class VoteController: UIViewController {
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var markdownView: MarkdownView!
let provider = VoteProvider()
override func viewDidLoad() {
self.pickerView.delegate = self
self.pickerView.dataSource = self
self.provider.list({ (_) in
self.pickerView.reloadAllComponents()
self.loadData(id: self.provider.list[0].id)
})
}
override func viewWillAppear(_ animated: Bool) {
self.tabBarController!.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "投票", style: .plain, target: self, action: #selector(vote))
}
@objc func vote() {
if provider.detail == nil {
return
}
self.performSegue(withIdentifier: "showSubmit", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destination = segue.destination as! VoteSubmitController
destination.provider = self.provider
}
func loadData(id: UUID) {
self.provider.detail(id: id, { (_) in
self.markdownView.load(markdown: self.provider.detail?.content ?? "", enableImage: true)
})
}
}
extension VoteController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return provider.list.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return provider.list[row].title
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.loadData(id: provider.list[row].id)
}
}
| apache-2.0 | be7ea7b105bf69896b4485ae8580353a | 29.686567 | 149 | 0.649805 | 4.662132 | false | false | false | false |
Senspark/ee-x | src/ios/ee/core/Utils.swift | 1 | 1132 | //
// Utils.swift
// ee-x-df17f84c
//
// Created by eps on 6/3/20.
//
import Foundation
public class Utils: NSObject {
#if os(iOS)
@objc
public class func getCurrentRootViewController() -> UIViewController? {
return UIApplication.shared.keyWindow?.rootViewController
}
@objc
public class func isLandscape() -> Bool {
return UIApplication.shared.statusBarOrientation.isLandscape
}
#endif // os(iOS)
@objc
public class func toString(_ value: Bool) -> String {
return value ? "true" : "false"
}
@objc
public class func toBool(_ value: String) -> Bool {
assert(value == "true" || value == "false", "Unexpected value: \(value)")
return value == "true"
}
@objc
public class func convertDpToPixels(_ dp: Float) -> Float {
return dp * Platform.getDensity()
}
@objc
public class func convertPixelsToDp(_ pixels: Float) -> Float {
return pixels / Platform.getDensity()
}
}
@_cdecl("ee_staticLog")
public func ee_staticLog(_ message: UnsafePointer<CChar>) {
print(String(cString: message))
}
| mit | ac399a2aa4c6bec6d3de825778038e54 | 22.583333 | 81 | 0.623675 | 3.944251 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/ObjectMapperTests/NestedKeysTests.swift | 10 | 6380 | //
// NestedKeysTests.swift
// ObjectMapper
//
// Created by Syo Ikeda on 3/10/15.
// Copyright (c) 2015 hearst. All rights reserved.
//
import Foundation
import XCTest
import ObjectMapper
import Nimble
class NestedKeysTests: 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 testNestedKeys() {
let JSON: [String: AnyObject] = [
"non.nested.key": "string",
"nested": [
"int64": NSNumber(longLong: INT64_MAX),
"bool": true,
"int": 255,
"double": 100.0 as Double,
"float": 50.0 as Float,
"string": "String!",
"nested": [
"int64Array": [NSNumber(longLong: INT64_MAX), NSNumber(longLong: INT64_MAX - 1), NSNumber(longLong: INT64_MAX - 10)],
"boolArray": [false, true, false],
"intArray": [1, 2, 3],
"doubleArray": [1.0, 2.0, 3.0],
"floatArray": [1.0 as Float, 2.0 as Float, 3.0 as Float],
"stringArray": ["123", "ABC"],
"int64Dict": ["1": NSNumber(longLong: INT64_MAX)],
"boolDict": ["2": true],
"intDict": ["3": 999],
"doubleDict": ["4": 999.999],
"floatDict": ["5": 123.456 as Float],
"stringDict": ["6": "InDict"],
"int64Enum": 1000,
"intEnum": 255,
"doubleEnum": 100.0,
"floatEnum": 100.0,
"stringEnum": "String B",
"nested": [
"object": ["value": 987],
"objectArray": [ ["value": 123], ["value": 456] ],
"objectDict": ["key": ["value": 999]]
]
]
]
]
let mapper = Mapper<NestedKeys>()
let value: NestedKeys! = mapper.map(JSON)
expect(value).notTo(beNil())
let JSONFromValue = mapper.toJSON(value)
let valueFromParsedJSON: NestedKeys! = mapper.map(JSONFromValue)
expect(valueFromParsedJSON).notTo(beNil())
expect(value.nonNestedString!).to(equal(valueFromParsedJSON.nonNestedString))
expect(value.int64).to(equal(valueFromParsedJSON.int64))
expect(value.bool).to(equal(valueFromParsedJSON.bool))
expect(value.int).to(equal(valueFromParsedJSON.int))
expect(value.double).to(equal(valueFromParsedJSON.double))
expect(value.float).to(equal(valueFromParsedJSON.float))
expect(value.string).to(equal(valueFromParsedJSON.string))
expect(value.int64Array).to(equal(valueFromParsedJSON.int64Array))
expect(value.boolArray).to(equal(valueFromParsedJSON.boolArray))
expect(value.intArray).to(equal(valueFromParsedJSON.intArray))
expect(value.doubleArray).to(equal(valueFromParsedJSON.doubleArray))
expect(value.floatArray).to(equal(valueFromParsedJSON.floatArray))
expect(value.stringArray).to(equal(valueFromParsedJSON.stringArray))
expect(value.int64Dict).to(equal(valueFromParsedJSON.int64Dict))
expect(value.boolDict).to(equal(valueFromParsedJSON.boolDict))
expect(value.intDict).to(equal(valueFromParsedJSON.intDict))
expect(value.doubleDict).to(equal(valueFromParsedJSON.doubleDict))
expect(value.floatDict).to(equal(valueFromParsedJSON.floatDict))
expect(value.stringDict).to(equal(valueFromParsedJSON.stringDict))
expect(value.int64Enum).to(equal(valueFromParsedJSON.int64Enum))
expect(value.intEnum).to(equal(valueFromParsedJSON.intEnum))
expect(value.doubleEnum).to(equal(valueFromParsedJSON.doubleEnum))
expect(value.floatEnum).to(equal(valueFromParsedJSON.floatEnum))
expect(value.stringEnum).to(equal(valueFromParsedJSON.stringEnum))
expect(value.object).to(equal(valueFromParsedJSON.object))
expect(value.objectArray).to(equal(valueFromParsedJSON.objectArray))
expect(value.objectDict).to(equal(valueFromParsedJSON.objectDict))
}
}
class NestedKeys: Mappable {
var nonNestedString: String?
var int64: NSNumber?
var bool: Bool?
var int: Int?
var double: Double?
var float: Float?
var string: String?
var int64Array: [NSNumber] = []
var boolArray: [Bool] = []
var intArray: [Int] = []
var doubleArray: [Double] = []
var floatArray: [Float] = []
var stringArray: [String] = []
var int64Dict: [String: NSNumber] = [:]
var boolDict: [String: Bool] = [:]
var intDict: [String: Int] = [:]
var doubleDict: [String: Double] = [:]
var floatDict: [String: Float] = [:]
var stringDict: [String: String] = [:]
var int64Enum: Int64Enum?
var intEnum: IntEnum?
var doubleEnum: DoubleEnum?
var floatEnum: FloatEnum?
var stringEnum: StringEnum?
var object: Object?
var objectArray: [Object] = []
var objectDict: [String: Object] = [:]
required init?(_ map: Map){
}
func mapping(map: Map) {
nonNestedString <- map["non.nested.key", nested: false]
int64 <- map["nested.int64"]
bool <- map["nested.bool"]
int <- map["nested.int"]
double <- map["nested.double"]
float <- map["nested.float"]
string <- map["nested.string"]
int64Array <- map["nested.nested.int64Array"]
boolArray <- map["nested.nested.boolArray"]
intArray <- map["nested.nested.intArray"]
doubleArray <- map["nested.nested.doubleArray"]
floatArray <- map["nested.nested.floatArray"]
stringArray <- map["nested.nested.stringArray"]
int64Dict <- map["nested.nested.int64Dict"]
boolDict <- map["nested.nested.boolDict"]
intDict <- map["nested.nested.intDict"]
doubleDict <- map["nested.nested.doubleDict"]
floatDict <- map["nested.nested.floatDict"]
stringDict <- map["nested.nested.stringDict"]
int64Enum <- map["nested.nested.int64Enum"]
intEnum <- map["nested.nested.intEnum"]
doubleEnum <- map["nested.nested.doubleEnum"]
floatEnum <- map["nested.nested.floatEnum"]
stringEnum <- map["nested.nested.stringEnum"]
object <- map["nested.nested.nested.object"]
objectArray <- map["nested.nested.nested.objectArray"]
objectDict <- map["nested.nested.nested.objectDict"]
}
}
class Object: Mappable, Equatable {
var value: Int = Int.min
required init?(_ map: Map){
}
func mapping(map: Map) {
value <- map["value"]
}
}
func == (lhs: Object, rhs: Object) -> Bool {
return lhs.value == rhs.value
}
enum Int64Enum: NSNumber {
case A = 0
case B = 1000
}
enum IntEnum: Int {
case A = 0
case B = 255
}
enum DoubleEnum: Double {
case A = 0.0
case B = 100.0
}
enum FloatEnum: Float {
case A = 0.0
case B = 100.0
}
enum StringEnum: String {
case A = "String A"
case B = "String B"
}
| mit | 026b86c9036cc5de76326967bae6a6af | 27.230088 | 122 | 0.687304 | 3.209256 | false | false | false | false |
wangxin20111/WXWeiBo | WXWeibo/WXWeibo/Classes/Lib/UIView+Category.swift | 1 | 1090 | //
// UIView+Category.swift
// WXWeibo
//
// Created by 王鑫 on 16/7/20.
// Copyright © 2016年 王鑫. All rights reserved.
//
import UIKit
extension UIView
{
//set,get -> X
func x() -> CGFloat
{
return self.frame.origin.x
}
func setX(x:CGFloat)
{
var frame = self.frame
frame.origin.x = x
self.frame = frame
}
//set,get -> Y
func y() -> CGFloat {
return self.frame.origin.y
}
func setY(y:CGFloat)
{
var frame = self.frame
frame.origin.y = y
self.frame = frame
}
//set,get ->Width
func width() -> CGFloat
{
return self.frame.size.width
}
func setWidht(width:CGFloat)
{
var frame = self.frame
frame.size.width = width
self.frame = frame
}
//set,get -> height
func height() -> CGFloat
{
return self.frame.size.height
}
func setHeight(height:CGFloat)
{
var frame = self.frame
frame.size.height = height
self.frame = frame
}
}
| mit | 2e539ad8fd3986f3343e91a47c0f565e | 16.655738 | 46 | 0.52182 | 3.650847 | false | false | false | false |
willowtreeapps/go-timestamp-example | ios/Timestamps/ViewController.swift | 1 | 2608 | //
// ViewController.swift
// Timestamps
//
// Created by Ian Terrell on 10/9/15.
// Copyright © 2015 WillowTree Apps. All rights reserved.
//
import UIKit
import Timestamp
struct TS: CustomStringConvertible {
static var Formatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.LongStyle
formatter.timeStyle = .MediumStyle
return formatter
}()
let time: NSDate
init(json: NSDictionary) {
let s = json["seconds_since_epoch"] as! NSNumber
time = NSDate(timeIntervalSince1970: s.doubleValue)
}
static func parse(jsonData: NSData) throws -> [TS] {
let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments) as! NSArray
var timestamps = [TS]()
for case let dict as NSDictionary in json {
timestamps.append(TS(json: dict))
}
return timestamps
}
var description: String {
return TS.Formatter.stringFromDate(time)
}
}
class ViewController: UITableViewController {
var timestamps = [TS]()
override func viewDidLoad() {
super.viewDidLoad()
reloadTimestamps()
}
func reloadTimestamps() {
var data: NSData?
var error: NSError?
Timestamp.GoTimestampAllJSON(&data, &error)
guard error == nil else {
print("Error getting timestamps: \(error)")
return
}
do {
timestamps = try TS.parse(data!)
} catch {
print("Error parsing timestamps: \(error)")
}
tableView.reloadData()
}
@IBAction func addTimestamp(sender: AnyObject) {
var error: NSError?
let now = NSDate().timeIntervalSince1970
Timestamp.GoTimestampInsert(Int64(now), &error)
guard error == nil else {
print("Error inserting timestamp: \(error)")
return
}
reloadTimestamps()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return timestamps.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TimestampCell")!
cell.textLabel?.text = timestamps[indexPath.row].description
return cell
}
}
| mit | 67929eb685043dd1b08a48a10e2ad43a | 26.442105 | 118 | 0.613349 | 5.172619 | false | false | false | false |
nanthi1990/CVCalendar | CVCalendar/CVAuxiliaryView.swift | 8 | 4336 | //
// CVAuxiliaryView.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 22/03/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
public final class CVAuxiliaryView: UIView {
public var shape: CVShape!
public var strokeColor: UIColor! {
didSet {
setNeedsDisplay()
}
}
public var fillColor: UIColor! {
didSet {
setNeedsDisplay()
}
}
public let defaultFillColor = UIColor.colorFromCode(0xe74c3c)
private var radius: CGFloat {
get {
return (min(frame.height, frame.width) - 10) / 2
}
}
public unowned let dayView: DayView
public init(dayView: DayView, rect: CGRect, shape: CVShape) {
self.dayView = dayView
self.shape = shape
super.init(frame: rect)
strokeColor = UIColor.clearColor()
fillColor = UIColor.colorFromCode(0xe74c3c)
layer.cornerRadius = 5
backgroundColor = .clearColor()
}
public override func didMoveToSuperview() {
setNeedsDisplay()
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
var path: UIBezierPath!
if let shape = shape {
switch shape {
case .RightFlag: path = rightFlagPath()
case .LeftFlag: path = leftFlagPath()
case .Circle: path = circlePath()
case .Rect: path = rectPath()
}
}
strokeColor.setStroke()
fillColor.setFill()
if let path = path {
path.lineWidth = 1
path.stroke()
path.fill()
}
}
deinit {
//println("[CVCalendar Recovery]: AuxiliaryView is deinited.")
}
}
extension CVAuxiliaryView {
public func updateFrame(frame: CGRect) {
self.frame = frame
setNeedsDisplay()
}
}
extension CVAuxiliaryView {
func circlePath() -> UIBezierPath {
let arcCenter = CGPointMake(frame.width / 2, frame.height / 2)
let startAngle = CGFloat(0)
let endAngle = CGFloat(M_PI * 2.0)
let clockwise = true
let path = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise)
return path
}
func rightFlagPath() -> UIBezierPath {
let appearance = dayView.calendarView.appearance
let offset = appearance.spaceBetweenDayViews!
let flag = UIBezierPath()
flag.moveToPoint(CGPointMake(bounds.width / 2, bounds.height / 2 - radius))
flag.addLineToPoint(CGPointMake(bounds.width, bounds.height / 2 - radius))
flag.addLineToPoint(CGPointMake(bounds.width, bounds.height / 2 + radius ))
flag.addLineToPoint(CGPointMake(bounds.width / 2, bounds.height / 2 + radius))
var path = CGPathCreateMutable()
CGPathAddPath(path, nil, circlePath().CGPath)
CGPathAddPath(path, nil, flag.CGPath)
return UIBezierPath(CGPath: path)
}
func leftFlagPath() -> UIBezierPath {
let flag = UIBezierPath()
flag.moveToPoint(CGPointMake(bounds.width / 2, bounds.height / 2 + radius))
flag.addLineToPoint(CGPointMake(0, bounds.height / 2 + radius))
flag.addLineToPoint(CGPointMake(0, bounds.height / 2 - radius))
flag.addLineToPoint(CGPointMake(bounds.width / 2, bounds.height / 2 - radius))
var path = CGPathCreateMutable()
CGPathAddPath(path, nil, circlePath().CGPath)
CGPathAddPath(path, nil, flag.CGPath)
return UIBezierPath(CGPath: path)
}
func rectPath() -> UIBezierPath {
let midX = bounds.width / 2
let midY = bounds.height / 2
let appearance = dayView.calendarView.appearance
let offset = appearance.spaceBetweenDayViews!
println("offset = \(offset)")
let path = UIBezierPath(rect: CGRectMake(0 - offset, midY - radius, bounds.width + offset / 2, radius * 2))
return path
}
} | mit | 928249c85aaff482fa0790191d9e8f38 | 28.705479 | 135 | 0.59202 | 4.839286 | false | false | false | false |
IamAlchemist/DemoDynamicCollectionView | DemoDynamicCollectionView/PinterestCell.swift | 1 | 985 | //
// PinterestCell.swift
// DemoDynamicCollectionView
//
// Created by wizard on 1/13/16.
// Copyright © 2016 morgenworks. All rights reserved.
//
import UIKit
class PinterestCell : UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var captionLabel: UILabel!
@IBOutlet weak var commentLabel: UILabel!
@IBOutlet weak var imageHeightConstraint: NSLayoutConstraint!
}
extension PinterestCell {
func configCell(photo: Photo){
captionLabel.text = photo.caption
commentLabel.text = photo.comment
imageView.image = photo.image
layer.cornerRadius = 8
layer.masksToBounds = true
}
}
extension PinterestCell {
override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes) {
super.applyLayoutAttributes(layoutAttributes)
imageHeightConstraint.constant = (layoutAttributes as! PinterestViewLayoutAttributes).photoHeight
}
} | mit | dec9312604d80253206ee40de4afbc78 | 26.361111 | 105 | 0.721545 | 5.072165 | false | false | false | false |
zoeyzhong520/InformationTechnology | InformationTechnology/InformationTechnology/Classes/Recommend推荐/Main主要模块/View/RecommendView.swift | 1 | 4261 | //
// RecommendView.swift
// InformationTechnology
//
// Created by qianfeng on 16/11/1.
// Copyright © 2016年 zzj. All rights reserved.
//
import UIKit
class RecommendView: UIView {
//定义科技页面cell的布局类型
enum ScienceCellType:String {
case topic2 = "topic2"
case doc = "doc"
case slide = "slide"
case text_live = "text_live"
}
//点击事件
var jumpClosure:RecommendJumpClosure?
//数据
var model:RecommendValueZero? {
didSet {
//set方法调用之后会调用这里的方法
tableView?.reloadData()
}
}
//广告数据
var adModel:RecommendValueOne? {
didSet {
tableView?.reloadData()
}
}
//表格
var tableView:UITableView?
//重新实现初始化方法
override init(frame: CGRect) {
super.init(frame: frame)
//创建表格视图
tableView = UITableView(frame: CGRectZero, style: .Plain)
tableView?.delegate = self
tableView?.dataSource = self
addSubview(tableView!)
//约束
tableView?.snp_makeConstraints(closure: { (make) in
make.edges.equalTo(self)
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK:UITableView的代理方法
extension RecommendView:UITableViewDelegate,UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var row = 0
if model?.item?.count > 0 {
row = (model?.item?.count)!+1
}
return row
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var height:CGFloat = 0
if indexPath.row == 0 {
height = 180
}else{
let itemModel = model?.item![indexPath.row-1]
if itemModel?.type == ScienceCellType.doc.rawValue || itemModel?.type == ScienceCellType.topic2.rawValue {
height = 110
}else if itemModel?.type == ScienceCellType.slide.rawValue {
height = 160
}else if itemModel?.type == ScienceCellType.text_live.rawValue {
height = 180
}
}
return height
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
//广告
let cell = RecommendHeaderCell.createHeaderCellFor(tableView, atIndexPath: indexPath, itemArray: adModel?.item)
//点击事件的响应代码
cell.jumpClosure = jumpClosure
return cell
}else{
//新闻部分
let itemModel = model?.item?[indexPath.row-1]
if itemModel?.type == ScienceCellType.doc.rawValue || itemModel?.type == ScienceCellType.topic2.rawValue {
let cell = RecommendScienceCell.createScienceCellFor(tableView, atIndexPath: indexPath, itemArray: [itemModel!])
//点击事件的响应代码
cell.jumpClosure = jumpClosure
return cell
}else if itemModel?.type == ScienceCellType.slide.rawValue {
let cell = HasTypeSlideCell.createHasTypeSlideCellFor(tableView, atIndexPath: indexPath, itemArray: [itemModel!])
//点击事件的响应代码
cell.jumpClosure = jumpClosure
return cell
}else if itemModel?.type == ScienceCellType.text_live.rawValue {
let cell = HasTypeLiveCell.createHasTypeLiveCellFor(tableView, atIndexPath: indexPath, itemArray: [itemModel!])
//点击事件的响应代码
cell.jumpClosure = jumpClosure
return cell
}
}
return UITableViewCell()
}
}
| mit | 540fdbf7edcaa923733cc4083b0e3f91 | 25.509804 | 129 | 0.543886 | 5.24031 | false | false | false | false |
jeffreybergier/WaterMe2 | WaterMe/WaterMe/ReminderVesselMain/ReminderEdit/ReminderEditTableViewController.swift | 1 | 14692 | //
// ReminderEditTableViewController.swift
// WaterMe
//
// Created by Jeffrey Bergier on 6/22/17.
// Copyright © 2017 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// WaterMe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import Datum
import UIKit
protocol ReminderEditTableViewControllerDelegate: class {
var reminderResult: Result<Reminder, DatumError>? { get }
func userChangedKind(to newKind: ReminderKind,
byUsingKeyboard usingKeyboard: Bool,
within: ReminderEditTableViewController)
func userDidSelectChangeInterval(popoverSourceView: UIView?,
deselectHandler: @escaping () -> Void,
within: ReminderEditTableViewController)
func userChangedNote(toNewNote newNote: String,
within: ReminderEditTableViewController)
func userDidSelect(siriShortcut: ReminderEditTableViewController.SiriShortcut,
deselectRowAnimated: ((Bool) -> Void)?,
within: ReminderEditTableViewController)
}
class ReminderEditTableViewController: StandardTableViewController {
weak var delegate: ReminderEditTableViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.clearsSelectionOnViewWillAppear = false
self.tableView.register(TextViewTableViewCell.nib,
forCellReuseIdentifier: TextViewTableViewCell.reuseID)
self.tableView.register(TextFieldTableViewCell.nib,
forCellReuseIdentifier: TextFieldTableViewCell.reuseID)
self.tableView.register(ReminderKindTableViewCell.self,
forCellReuseIdentifier: ReminderKindTableViewCell.reuseID)
self.tableView.register(ReminderIntervalTableViewCell.self,
forCellReuseIdentifier: ReminderIntervalTableViewCell.reuseID)
self.tableView.register(SiriShortcutTableViewCell.self,
forCellReuseIdentifier: SiriShortcutTableViewCell.reuseID)
self.tableView.register(LastPerformedTableViewCell.self,
forCellReuseIdentifier: LastPerformedTableViewCell.reuseID)
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.estimatedRowHeight = 40
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let reminder = self.delegate?.reminderResult?.value else {
assertionFailure("Missing Reminder Object")
return
}
let section = Section(section: indexPath.section, for: reminder.kind)
switch section {
case .kind:
self.tableView.deselectRow(at: indexPath, animated: true)
// let the deselection happen before changing the tableview
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
let new = ReminderKind(row: indexPath.row)
self.delegate?.userChangedKind(to: new,
byUsingKeyboard: false,
within: self)
}
case .interval:
self.delegate?.userDidSelectChangeInterval(
popoverSourceView: tableView.cellForRow(at: indexPath),
deselectHandler: {
tableView.deselectRow(at: indexPath, animated: true)
},
within: self)
case .siriShortcuts:
guard let shortcut = SiriShortcut(rawValue: indexPath.row) else { return }
let closure = { (anim: Bool) -> Void in
tableView.deselectRow(at: indexPath, animated: anim)
}
self.delegate?.userDidSelect(siriShortcut: shortcut,
deselectRowAnimated: closure,
within: self)
case .details, .notes, .performed:
assertionFailure("User was allowed to select unselectable row")
}
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
guard let reminder = self.delegate?.reminderResult?.value else {
assertionFailure("Missing Reminder Object")
return nil
}
let section = Section(section: indexPath.section, for: reminder.kind)
switch section {
case .details, .notes, .performed:
return nil
case .kind, .interval, .siriShortcuts:
return indexPath
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
guard let reminder = self.delegate?.reminderResult?.value else { return 0 }
return Section.count(for: reminder.kind)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let reminder = self.delegate?.reminderResult?.value else {
assertionFailure("Missing Reminder Object")
return 0
}
let section = Section(section: section, for: reminder.kind)
return section.numberOfRows(for: reminder.kind)
}
//swiftlint:disable:next function_body_length
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let reminder = self.delegate?.reminderResult?.value else {
assertionFailure("Missing Reminder Object")
return UITableViewCell()
}
let section = Section(section: indexPath.section, for: reminder.kind)
switch section {
case .kind:
let id = ReminderKindTableViewCell.reuseID
let _cell = tableView.dequeueReusableCell(withIdentifier: id, for: indexPath)
let cell = _cell as? ReminderKindTableViewCell
cell?.configure(rowNumber: indexPath.row, compareWith: reminder.kind)
return _cell
case .details:
let id = TextFieldTableViewCell.reuseID
let _cell = tableView.dequeueReusableCell(withIdentifier: id, for: indexPath)
let cell = _cell as? TextFieldTableViewCell
cell?.configure(with: reminder.kind)
cell?.textChanged = { [unowned self] newText in
self.updated(text: newText, for: reminder.kind)
}
return _cell
case .interval:
let id = ReminderIntervalTableViewCell.reuseID
let _cell = tableView.dequeueReusableCell(withIdentifier: id, for: indexPath)
let cell = _cell as? ReminderIntervalTableViewCell
cell?.configure(with: reminder.interval)
return _cell
case .notes:
let id = TextViewTableViewCell.reuseID
let _cell = tableView.dequeueReusableCell(withIdentifier: id, for: indexPath)
let cell = _cell as? TextViewTableViewCell
cell?.configure(with: reminder.note)
cell?.textChanged = { [unowned self] newText in
self.delegate?.userChangedNote(toNewNote: newText, within: self)
}
return _cell
case .siriShortcuts:
let id = SiriShortcutTableViewCell.reuseID
let _cell = tableView.dequeueReusableCell(withIdentifier: id, for: indexPath)
guard
let cell = _cell as? SiriShortcutTableViewCell,
let row = SiriShortcut(rawValue: indexPath.row)
else { return _cell }
cell.configure(withLocalizedTitle: row.localizedTitle)
return cell
case .performed:
let id = LastPerformedTableViewCell.reuseID
let _cell = tableView.dequeueReusableCell(withIdentifier: id, for: indexPath)
let cell = _cell as? LastPerformedTableViewCell
cell?.configureWith(lastPerformedDate: reminder.lastPerformDate)
return _cell
}
}
func forceTextFieldToBecomeFirstResponder() {
guard let reminder = self.delegate?.reminderResult?.value else {
assertionFailure("Missing Reminder Object")
return
}
let reminderKind = reminder.kind
switch reminderKind {
case .other, .move:
let indexPath = IndexPath(row: 0, section: 1)
UIView.style_animateNormal({
self.tableView.scrollToRow(at: indexPath, at: .top, animated: false)
}, completion: { _ in
let cell = self.tableView.cellForRow(at: indexPath) as? TextFieldTableViewCell
cell?.textFieldBecomeFirstResponder()
})
case .fertilize, .water, .trim, .mist:
assertionFailure("Water and Fertilize Reminders don't have a textfield to select")
}
}
override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.view.endEditing(false)
}
private func updated(text newText: String, for oldKind: ReminderKind) {
let newKind: ReminderKind
defer {
self.delegate?.userChangedKind(to: newKind,
byUsingKeyboard: true,
within: self)
}
switch oldKind {
case .move:
newKind = ReminderKind.move(location: newText)
case .other:
newKind = ReminderKind.other(description: newText)
default:
fatalError("Wrong Kind Encountered")
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let reminder = self.delegate?.reminderResult?.value else {
assertionFailure("Missing Reminder Object")
return nil
}
let section = Section(section: section, for: reminder.kind)
return section.localizedString
}
}
extension ReminderEditTableViewController {
enum SiriShortcut: Int, CaseIterable {
case editReminder, viewReminder, performReminder
var localizedTitle: String {
switch self {
case .editReminder:
return UIApplication.LocalizedString.editReminder
case .viewReminder:
return ReminderEditViewController.LocalizedString.viewReminderShortcutLabelText
case .performReminder:
return ReminderMainViewController.LocalizedString.buttonTitleReminderPerform
}
}
}
private enum Section {
case kind, details, interval, notes, siriShortcuts, performed
static func count(for kind: ReminderKind) -> Int {
switch kind {
case .fertilize, .water, .trim, .mist:
return 5
case .other, .move:
return 6
}
}
// swiftlint:disable:next cyclomatic_complexity
init(section: Int, for kind: ReminderKind) {
switch kind {
case .fertilize, .water, .trim, .mist:
switch section {
case 0:
self = .kind
case 1:
self = .interval
case 2:
self = .notes
case 3:
self = .siriShortcuts
case 4:
self = .performed
default:
fatalError("Invalid Section")
}
case .other, .move:
switch section {
case 0:
self = .kind
case 1:
self = .details
case 2:
self = .interval
case 3:
self = .notes
case 4:
self = .siriShortcuts
case 5:
self = .performed
default:
fatalError("Invalid Section")
}
}
}
var localizedString: String {
switch self {
case .kind:
return ReminderEditViewController.LocalizedString.sectionTitleKind
case .details:
return ReminderEditViewController.LocalizedString.sectionTitleDetails
case .interval:
return ReminderEditViewController.LocalizedString.sectionTitleInterval
case .notes:
return ReminderEditViewController.LocalizedString.sectionTitleNotes
case .siriShortcuts:
return "Siri Shortcuts"
case .performed:
return ReminderEditViewController.LocalizedString.sectionTitleLastPerformed
}
}
func numberOfRows(for kind: ReminderKind) -> Int {
switch self {
case .kind:
return type(of: kind).count
case .siriShortcuts:
return SiriShortcut.allCases.count
case .details, .performed, .interval, .notes:
return 1
}
}
}
}
fileprivate extension TextFieldTableViewCell {
func configure(with kind: ReminderKind) {
switch kind {
case .move(let location):
self.setLabelText(ReminderEditViewController.LocalizedString.dataEntryLabelMove,
andTextFieldPlaceHolderText: ReminderEditViewController.LocalizedString.dataEntryPlaceholderMove)
self.setTextField(text: location)
case .other(let description):
self.setLabelText(ReminderEditViewController.LocalizedString.dataEntryLabelDescription,
andTextFieldPlaceHolderText: ReminderEditViewController.LocalizedString.dataEntryPlaceholderDescription)
self.setTextField(text: description)
default:
let error = "Unsupported Kind: \(kind)"
log.error(error)
assertionFailure(error)
}
}
}
| gpl-3.0 | 1d118ffe1be788657d86ee0a552c1684 | 41.582609 | 134 | 0.59853 | 5.635213 | false | false | false | false |
zmarvin/EnjoyMusic | Pods/Macaw/Source/views/ShapeLayer.swift | 1 | 626 | import UIKit
class ShapeLayer: CAShapeLayer {
var node: Node?
var renderTransform: CGAffineTransform?
var animationCache: AnimationCache?
override func draw(in ctx: CGContext) {
guard let node = node else {
return
}
guard let animationCache = animationCache else {
return
}
let renderContext = RenderContext(view: .none)
renderContext.cgContext = ctx
if let renderTransform = renderTransform {
ctx.concatenate(renderTransform)
}
let renderer = RenderUtils.createNodeRenderer(node, context: renderContext, animationCache: animationCache)
renderer.directRender()
renderer.dispose()
}
}
| mit | 380b56cea88aa8b8232b7cb400efb10c | 21.357143 | 109 | 0.750799 | 3.864198 | false | false | false | false |
ZekeSnider/Jared | Jared/DatabaseHandler.swift | 1 | 10695 | //
// DatabaseHandler.swift
// JaredUI
//
// Created by Zeke Snider on 11/9/18.
// Copyright © 2018 Zeke Snider. All rights reserved.
//
internal let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
internal let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
import JaredFramework
import SQLite3
class DatabaseHandler {
private static let groupQuery = """
SELECT handle.id, display_name, chat.guid
FROM chat_handle_join INNER JOIN handle ON chat_handle_join.handle_id = handle.ROWID
INNER JOIN chat ON chat_handle_join.chat_id = chat.ROWID
WHERE chat.chat_identifier = ?
"""
private static let attachmentQuery = """
SELECT ROWID,
filename,
mime_type,
transfer_name,
is_sticker
FROM attachment
INNER JOIN message_attachment_join
ON attachment.ROWID = message_attachment_join.attachment_id
WHERE message_id = ?
"""
private static let newRecordquery = """
SELECT handle.id, message.text, message.ROWID, message.cache_roomnames, message.is_from_me, message.destination_caller_id,
message.date/1000000000 + strftime("%s", "2001-01-01"),
message.cache_has_attachments,
message.expressive_send_style_id,
message.associated_message_type,
message.associated_message_guid, message.guid, destination_caller_id
FROM message LEFT JOIN handle
ON message.handle_id = handle.ROWID
WHERE message.ROWID > ? ORDER BY message.ROWID ASC
"""
private static let maxRecordIDQuery = "SELECT MAX(rowID) FROM message"
var db: OpaquePointer?
var querySinceID: String?
var shouldExitThread = false
var refreshSeconds = 5.0
var statement: OpaquePointer? = nil
var router: RouterDelegate?
init(router: RouterDelegate, databaseLocation: URL, diskAccessDelegate: DiskAccessDelegate?) {
self.router = router
if sqlite3_open(databaseLocation.path, &db) != SQLITE_OK {
NSLog("Error opening SQLite database. Likely Full disk access error.")
UserDefaults.standard.set(false, forKey: JaredConstants.fullDiskAccess)
diskAccessDelegate?.displayAccessError()
return
}
UserDefaults.standard.set(true, forKey: JaredConstants.fullDiskAccess)
querySinceID = getCurrentMaxRecordID()
start()
}
deinit {
shouldExitThread = true
if sqlite3_close(db) != SQLITE_OK {
print("error closing database")
}
db = nil
}
func start() {
let dispatchQueue = DispatchQueue(label: "Jared Background Thread", qos: .background)
dispatchQueue.async(execute: self.backgroundAction)
}
private func backgroundAction() {
while shouldExitThread == false {
let elapsed = queryNewRecords()
Thread.sleep(forTimeInterval: max(0, refreshSeconds - elapsed))
}
}
private func getCurrentMaxRecordID() -> String {
var id: String?
var statement: OpaquePointer?
if sqlite3_prepare_v2(db, DatabaseHandler.maxRecordIDQuery, -1, &statement, nil) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error preparing select: \(errmsg)")
}
while sqlite3_step(statement) == SQLITE_ROW {
guard let idcString = sqlite3_column_text(statement, 0) else {
break
}
id = String(cString: idcString)
}
if sqlite3_finalize(statement) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error finalizing prepared statement: \(errmsg)")
}
return id ?? "0"
}
private func retrieveGroupInfo(chatID: String?) -> Group? {
guard let chatHandle = chatID else {
return nil
}
var statement: OpaquePointer?
if sqlite3_prepare_v2(db, DatabaseHandler.groupQuery, -1, &statement, nil) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error preparing select: \(errmsg)")
}
if sqlite3_bind_text(statement, 1, chatID, -1, SQLITE_TRANSIENT) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("failure binding foo: \(errmsg)")
}
var People = [Person]()
var groupName: String?
var chatGUID: String?
while sqlite3_step(statement) == SQLITE_ROW {
guard let idcString = sqlite3_column_text(statement, 0) else {
break
}
groupName = unwrapStringColumn(for: statement, at: 1)
chatGUID = unwrapStringColumn(for: statement, at: 2)
let handle = String(cString: idcString)
let contact = ContactHelper.RetreiveContact(handle: handle)
People.append(Person(givenName: contact?.givenName, handle: handle, isMe: false))
}
return Group(name: groupName, handle: chatGUID ?? chatHandle, participants: People)
}
private func unwrapStringColumn(for sqlStatement: OpaquePointer?, at column: Int32) -> String? {
if let cString = sqlite3_column_text(sqlStatement, column) {
return String(cString: cString)
} else {
return nil
}
}
private func retrieveAttachments(forMessage messageID: String) -> [Attachment] {
var attachmentStatement: OpaquePointer? = nil
defer { attachmentStatement = nil }
if sqlite3_prepare_v2(db, DatabaseHandler.attachmentQuery, -1, &attachmentStatement, nil) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error preparing select: \(errmsg)")
}
if sqlite3_bind_text(attachmentStatement, 1, messageID, -1, SQLITE_TRANSIENT) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("failure binding: \(errmsg)")
}
var attachments = [Attachment]()
while sqlite3_step(attachmentStatement) == SQLITE_ROW {
guard let rowID = unwrapStringColumn(for: attachmentStatement, at: 0) else { continue }
guard let fileName = unwrapStringColumn(for: attachmentStatement, at: 1) else { continue }
guard let mimeType = unwrapStringColumn(for: attachmentStatement, at: 2) else { continue }
guard let transferName = unwrapStringColumn(for: attachmentStatement, at: 3) else { continue }
let isSticker = sqlite3_column_int(attachmentStatement, 4) == 1
attachments.append(Attachment(id: Int(rowID)!, filePath: fileName, mimeType: mimeType, fileName: transferName, isSticker: isSticker))
}
if sqlite3_finalize(attachmentStatement) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error finalizing prepared statement: \(errmsg)")
}
return attachments
}
private func queryNewRecords() -> Double {
let start = Date()
defer { statement = nil }
if sqlite3_prepare_v2(db, DatabaseHandler.newRecordquery, -1, &statement, nil) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error preparing select: \(errmsg)")
}
if sqlite3_bind_text(statement, 1, querySinceID ?? "1000000000", -1, SQLITE_TRANSIENT) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("failure binding: \(errmsg)")
}
while sqlite3_step(statement) == SQLITE_ROW {
var senderHandleOptional = unwrapStringColumn(for: statement, at: 0)
let textOptional = unwrapStringColumn(for: statement, at: 1)
let rowID = unwrapStringColumn(for: statement, at: 2)
let roomName = unwrapStringColumn(for: statement, at: 3)
let isFromMe = sqlite3_column_int(statement, 4) == 1
let destinationOptional = unwrapStringColumn(for: statement, at: 5)
let epochDate = TimeInterval(sqlite3_column_int64(statement, 6))
let hasAttachment = sqlite3_column_int(statement, 7) == 1
let sendStyle = unwrapStringColumn(for: statement, at: 8)
let associatedMessageType = sqlite3_column_int(statement, 9)
let associatedMessageGUID = unwrapStringColumn(for: statement, at: 10)
let guid = unwrapStringColumn(for: statement, at: 11)
let destinationCallerId = unwrapStringColumn(for: statement, at: 12)
NSLog("Processing \(rowID ?? "unknown")")
querySinceID = rowID;
if (senderHandleOptional == nil && isFromMe == true && roomName != nil) {
senderHandleOptional = destinationCallerId
}
guard let senderHandle = senderHandleOptional, let text = textOptional, let destination = destinationOptional else {
break
}
let buddyName = ContactHelper.RetreiveContact(handle: senderHandle)?.givenName
let myName = ContactHelper.RetreiveContact(handle: destination)?.givenName
let sender: Person
let recipient: RecipientEntity
let group = retrieveGroupInfo(chatID: roomName)
if (isFromMe) {
sender = Person(givenName: myName, handle: destination, isMe: true)
recipient = group ?? Person(givenName: buddyName, handle: senderHandle, isMe: false)
} else {
sender = Person(givenName: buddyName, handle: senderHandle, isMe: false)
recipient = group ?? Person(givenName: myName, handle: destination, isMe: true)
}
let message = Message(body: TextBody(text), date: Date(timeIntervalSince1970: epochDate), sender: sender, recipient: recipient, guid: guid, attachments: hasAttachment ? retrieveAttachments(forMessage: rowID ?? "") : [],
sendStyle: sendStyle, associatedMessageType: Int(associatedMessageType), associatedMessageGUID: associatedMessageGUID)
router?.route(message: message)
}
if sqlite3_finalize(statement) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error finalizing prepared statement: \(errmsg)")
}
return NSDate().timeIntervalSince(start)
}
}
| apache-2.0 | c9eff55c8762cae491dd25aeea1fe869 | 39.97318 | 231 | 0.614457 | 4.504634 | false | false | false | false |
ikesyo/swift-corelibs-foundation | Foundation/NSCalendar.swift | 1 | 81670 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
internal let kCFCalendarUnitEra = CFCalendarUnit.era.rawValue
internal let kCFCalendarUnitYear = CFCalendarUnit.year.rawValue
internal let kCFCalendarUnitMonth = CFCalendarUnit.month.rawValue
internal let kCFCalendarUnitDay = CFCalendarUnit.day.rawValue
internal let kCFCalendarUnitHour = CFCalendarUnit.hour.rawValue
internal let kCFCalendarUnitMinute = CFCalendarUnit.minute.rawValue
internal let kCFCalendarUnitSecond = CFCalendarUnit.second.rawValue
internal let kCFCalendarUnitWeekday = CFCalendarUnit.weekday.rawValue
internal let kCFCalendarUnitWeekdayOrdinal = CFCalendarUnit.weekdayOrdinal.rawValue
internal let kCFCalendarUnitQuarter = CFCalendarUnit.quarter.rawValue
internal let kCFCalendarUnitWeekOfMonth = CFCalendarUnit.weekOfMonth.rawValue
internal let kCFCalendarUnitWeekOfYear = CFCalendarUnit.weekOfYear.rawValue
internal let kCFCalendarUnitYearForWeekOfYear = CFCalendarUnit.yearForWeekOfYear.rawValue
internal let kCFDateFormatterNoStyle = CFDateFormatterStyle.noStyle
internal let kCFDateFormatterShortStyle = CFDateFormatterStyle.shortStyle
internal let kCFDateFormatterMediumStyle = CFDateFormatterStyle.mediumStyle
internal let kCFDateFormatterLongStyle = CFDateFormatterStyle.longStyle
internal let kCFDateFormatterFullStyle = CFDateFormatterStyle.fullStyle
#endif
extension NSCalendar {
public struct Identifier : RawRepresentable, Equatable, Hashable, Comparable {
public private(set) var rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static let gregorian = NSCalendar.Identifier("gregorian")
public static let buddhist = NSCalendar.Identifier("buddhist")
public static let chinese = NSCalendar.Identifier("chinese")
public static let coptic = NSCalendar.Identifier("coptic")
public static let ethiopicAmeteMihret = NSCalendar.Identifier("ethiopic")
public static let ethiopicAmeteAlem = NSCalendar.Identifier("ethiopic-amete-alem")
public static let hebrew = NSCalendar.Identifier("hebrew")
public static let ISO8601 = NSCalendar.Identifier("iso8601")
public static let indian = NSCalendar.Identifier("indian")
public static let islamic = NSCalendar.Identifier("islamic")
public static let islamicCivil = NSCalendar.Identifier("islamic-civil")
public static let japanese = NSCalendar.Identifier("japanese")
public static let persian = NSCalendar.Identifier("persian")
public static let republicOfChina = NSCalendar.Identifier("roc")
public static let islamicTabular = NSCalendar.Identifier("islamic-tbla")
public static let islamicUmmAlQura = NSCalendar.Identifier("islamic-umalqura")
}
public struct Unit: OptionSet {
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
public static let era = Unit(rawValue: UInt(kCFCalendarUnitEra))
public static let year = Unit(rawValue: UInt(kCFCalendarUnitYear))
public static let month = Unit(rawValue: UInt(kCFCalendarUnitMonth))
public static let day = Unit(rawValue: UInt(kCFCalendarUnitDay))
public static let hour = Unit(rawValue: UInt(kCFCalendarUnitHour))
public static let minute = Unit(rawValue: UInt(kCFCalendarUnitMinute))
public static let second = Unit(rawValue: UInt(kCFCalendarUnitSecond))
public static let weekday = Unit(rawValue: UInt(kCFCalendarUnitWeekday))
public static let weekdayOrdinal = Unit(rawValue: UInt(kCFCalendarUnitWeekdayOrdinal))
public static let quarter = Unit(rawValue: UInt(kCFCalendarUnitQuarter))
public static let weekOfMonth = Unit(rawValue: UInt(kCFCalendarUnitWeekOfMonth))
public static let weekOfYear = Unit(rawValue: UInt(kCFCalendarUnitWeekOfYear))
public static let yearForWeekOfYear = Unit(rawValue: UInt(kCFCalendarUnitYearForWeekOfYear))
public static let nanosecond = Unit(rawValue: UInt(1 << 15))
public static let calendar = Unit(rawValue: UInt(1 << 20))
public static let timeZone = Unit(rawValue: UInt(1 << 21))
internal var _cfValue: CFCalendarUnit {
#if os(OSX) || os(iOS)
return CFCalendarUnit(rawValue: self.rawValue)
#else
return CFCalendarUnit(self.rawValue)
#endif
}
}
public struct Options : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let wrapComponents = Options(rawValue: 1 << 0)
public static let matchStrictly = Options(rawValue: 1 << 1)
public static let searchBackwards = Options(rawValue: 1 << 2)
public static let matchPreviousTimePreservingSmallerUnits = Options(rawValue: 1 << 8)
public static let matchNextTimePreservingSmallerUnits = Options(rawValue: 1 << 9)
public static let matchNextTime = Options(rawValue: 1 << 10)
public static let matchFirst = Options(rawValue: 1 << 12)
public static let matchLast = Options(rawValue: 1 << 13)
}
}
extension NSCalendar.Identifier {
public static func ==(_ lhs: NSCalendar.Identifier, _ rhs: NSCalendar.Identifier) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func <(_ lhs: NSCalendar.Identifier, _ rhs: NSCalendar.Identifier) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
open class NSCalendar : NSObject, NSCopying, NSSecureCoding {
typealias CFType = CFCalendar
private var _base = _CFInfo(typeID: CFCalendarGetTypeID())
private var _identifier: UnsafeMutableRawPointer? = nil
private var _locale: UnsafeMutableRawPointer? = nil
private var _localeID: UnsafeMutableRawPointer? = nil
private var _tz: UnsafeMutableRawPointer? = nil
private var _cal: UnsafeMutableRawPointer? = nil
internal var _cfObject: CFType {
return unsafeBitCast(self, to: CFCalendar.self)
}
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
guard let calendarIdentifier = aDecoder.decodeObject(of: NSString.self, forKey: "NS.identifier") else {
return nil
}
self.init(identifier: NSCalendar.Identifier.init(rawValue: calendarIdentifier._swiftObject))
if let timeZone = aDecoder.decodeObject(of: NSTimeZone.self, forKey: "NS.timezone") {
self.timeZone = timeZone._swiftObject
}
if let locale = aDecoder.decodeObject(of: NSLocale.self, forKey: "NS.locale") {
self.locale = locale._swiftObject
}
self.firstWeekday = aDecoder.decodeInteger(forKey: "NS.firstwkdy")
self.minimumDaysInFirstWeek = aDecoder.decodeInteger(forKey: "NS.mindays")
if let startDate = aDecoder.decodeObject(of: NSDate.self, forKey: "NS.gstartdate") {
self._startDate = startDate._swiftObject
}
}
private var _startDate : Date? {
get {
return CFCalendarCopyGregorianStartDate(self._cfObject)?._swiftObject
}
set {
if let startDate = newValue {
CFCalendarSetGregorianStartDate(self._cfObject, startDate._cfObject)
}
}
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.calendarIdentifier.rawValue._bridgeToObjectiveC(), forKey: "NS.identifier")
aCoder.encode(self.timeZone._nsObject, forKey: "NS.timezone")
aCoder.encode(self.locale?._bridgeToObjectiveC(), forKey: "NS.locale")
aCoder.encode(self.firstWeekday, forKey: "NS.firstwkdy")
aCoder.encode(self.minimumDaysInFirstWeek, forKey: "NS.mindays")
aCoder.encode(self._startDate?._nsObject, forKey: "NS.gstartdate")
}
static public var supportsSecureCoding: Bool {
return true
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
let copy = NSCalendar(identifier: calendarIdentifier)!
copy.locale = locale
copy.timeZone = timeZone
copy.firstWeekday = firstWeekday
copy.minimumDaysInFirstWeek = minimumDaysInFirstWeek
copy._startDate = _startDate
return copy
}
open class var current: Calendar {
return CFCalendarCopyCurrent()._swiftObject
}
open class var autoupdatingCurrent: Calendar { NSUnimplemented() } // tracks changes to user's preferred calendar identifier
public /*not inherited*/ init?(identifier calendarIdentifierConstant: Identifier) {
super.init()
if !_CFCalendarInitWithIdentifier(_cfObject, calendarIdentifierConstant.rawValue._cfObject) {
return nil
}
}
public init?(calendarIdentifier ident: Identifier) {
super.init()
if !_CFCalendarInitWithIdentifier(_cfObject, ident.rawValue._cfObject) {
return nil
}
}
open override var hash: Int {
return Int(bitPattern: CFHash(_cfObject))
}
open override func isEqual(_ value: Any?) -> Bool {
switch value {
case let other as Calendar:
return CFEqual(_cfObject, other._cfObject)
case let other as NSCalendar:
return other === self || CFEqual(_cfObject, other._cfObject)
default:
return false
}
}
open override var description: String {
return CFCopyDescription(_cfObject)._swiftObject
}
deinit {
_CFDeinit(self)
}
open var calendarIdentifier: Identifier {
get {
return Identifier(rawValue: CFCalendarGetIdentifier(_cfObject)._swiftObject)
}
}
/*@NSCopying*/ open var locale: Locale? {
get {
return CFCalendarCopyLocale(_cfObject)._swiftObject
}
set {
CFCalendarSetLocale(_cfObject, newValue?._cfObject)
}
}
/*@NSCopying*/ open var timeZone: TimeZone {
get {
return CFCalendarCopyTimeZone(_cfObject)._swiftObject
}
set {
CFCalendarSetTimeZone(_cfObject, newValue._cfObject)
}
}
open var firstWeekday: Int {
get {
return CFCalendarGetFirstWeekday(_cfObject)
}
set {
CFCalendarSetFirstWeekday(_cfObject, CFIndex(newValue))
}
}
open var minimumDaysInFirstWeek: Int {
get {
return CFCalendarGetMinimumDaysInFirstWeek(_cfObject)
}
set {
CFCalendarSetMinimumDaysInFirstWeek(_cfObject, CFIndex(newValue))
}
}
// Methods to return component name strings localized to the calendar's locale
private func _symbols(_ key: CFString) -> [String] {
let dateFormatter = CFDateFormatterCreate(kCFAllocatorSystemDefault, locale?._cfObject, kCFDateFormatterNoStyle, kCFDateFormatterNoStyle)
CFDateFormatterSetProperty(dateFormatter, kCFDateFormatterCalendarKey, _cfObject)
let result = (CFDateFormatterCopyProperty(dateFormatter, key) as! CFArray)._swiftObject
return result.map {
return ($0 as! NSString)._swiftObject
}
}
private func _symbol(_ key: CFString) -> String {
let dateFormatter = CFDateFormatterCreate(kCFAllocatorSystemDefault, locale?._bridgeToObjectiveC()._cfObject, kCFDateFormatterNoStyle, kCFDateFormatterNoStyle)
CFDateFormatterSetProperty(dateFormatter, kCFDateFormatterCalendarKey, self._cfObject)
return (CFDateFormatterCopyProperty(dateFormatter, key) as! NSString)._swiftObject
}
open var eraSymbols: [String] {
return _symbols(kCFDateFormatterEraSymbolsKey)
}
open var longEraSymbols: [String] {
return _symbols(kCFDateFormatterLongEraSymbolsKey)
}
open var monthSymbols: [String] {
return _symbols(kCFDateFormatterMonthSymbolsKey)
}
open var shortMonthSymbols: [String] {
return _symbols(kCFDateFormatterShortMonthSymbolsKey)
}
open var veryShortMonthSymbols: [String] {
return _symbols(kCFDateFormatterVeryShortMonthSymbolsKey)
}
open var standaloneMonthSymbols: [String] {
return _symbols(kCFDateFormatterStandaloneMonthSymbolsKey)
}
open var shortStandaloneMonthSymbols: [String] {
return _symbols(kCFDateFormatterShortStandaloneMonthSymbolsKey)
}
open var veryShortStandaloneMonthSymbols: [String] {
return _symbols(kCFDateFormatterVeryShortStandaloneMonthSymbolsKey)
}
open var weekdaySymbols: [String] {
return _symbols(kCFDateFormatterWeekdaySymbolsKey)
}
open var shortWeekdaySymbols: [String] {
return _symbols(kCFDateFormatterShortWeekdaySymbolsKey)
}
open var veryShortWeekdaySymbols: [String] {
return _symbols(kCFDateFormatterVeryShortWeekdaySymbolsKey)
}
open var standaloneWeekdaySymbols: [String] {
return _symbols(kCFDateFormatterStandaloneWeekdaySymbolsKey)
}
open var shortStandaloneWeekdaySymbols: [String] {
return _symbols(kCFDateFormatterShortStandaloneWeekdaySymbolsKey)
}
open var veryShortStandaloneWeekdaySymbols: [String] {
return _symbols(kCFDateFormatterVeryShortStandaloneWeekdaySymbolsKey)
}
open var quarterSymbols: [String] {
return _symbols(kCFDateFormatterQuarterSymbolsKey)
}
open var shortQuarterSymbols: [String] {
return _symbols(kCFDateFormatterShortQuarterSymbolsKey)
}
open var standaloneQuarterSymbols: [String] {
return _symbols(kCFDateFormatterStandaloneQuarterSymbolsKey)
}
open var shortStandaloneQuarterSymbols: [String] {
return _symbols(kCFDateFormatterShortStandaloneQuarterSymbolsKey)
}
open var amSymbol: String {
return _symbol(kCFDateFormatterAMSymbolKey)
}
open var pmSymbol: String {
return _symbol(kCFDateFormatterPMSymbolKey)
}
// Calendrical calculations
open func minimumRange(of unit: Unit) -> NSRange {
let r = CFCalendarGetMinimumRangeOfUnit(self._cfObject, unit._cfValue)
if (r.location == kCFNotFound) {
return NSRange(location: NSNotFound, length: NSNotFound)
}
return NSRange(location: r.location, length: r.length)
}
open func maximumRange(of unit: Unit) -> NSRange {
let r = CFCalendarGetMaximumRangeOfUnit(_cfObject, unit._cfValue)
if r.location == kCFNotFound {
return NSRange(location: NSNotFound, length: NSNotFound)
}
return NSRange(location: r.location, length: r.length)
}
open func range(of smaller: Unit, in larger: Unit, for date: Date) -> NSRange {
let r = CFCalendarGetRangeOfUnit(_cfObject, smaller._cfValue, larger._cfValue, date.timeIntervalSinceReferenceDate)
if r.location == kCFNotFound {
return NSRange(location: NSNotFound, length: NSNotFound)
}
return NSRange(location: r.location, length: r.length)
}
open func ordinality(of smaller: Unit, in larger: Unit, for date: Date) -> Int {
return Int(CFCalendarGetOrdinalityOfUnit(_cfObject, smaller._cfValue, larger._cfValue, date.timeIntervalSinceReferenceDate))
}
/// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer.
/// The current exposed API in Foundation on Darwin platforms is:
/// open func rangeOfUnit(_ unit: Unit, startDate datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, forDate date: NSDate) -> Bool
/// which is not implementable on Linux due to the lack of being able to properly implement AutoreleasingUnsafeMutablePointer.
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func range(of unit: Unit, for date: Date) -> DateInterval? {
var start: CFAbsoluteTime = 0.0
var ti: CFTimeInterval = 0.0
let res: Bool = withUnsafeMutablePointer(to: &start) { startp in
withUnsafeMutablePointer(to: &ti) { tip in
return CFCalendarGetTimeRangeOfUnit(_cfObject, unit._cfValue, date.timeIntervalSinceReferenceDate, startp, tip)
}
}
if res {
return DateInterval(start: Date(timeIntervalSinceReferenceDate: start), duration: ti)
}
return nil
}
private func _convert(_ comp: Int?, type: String, vector: inout [Int32], compDesc: inout [Int8]) {
if let component = comp {
vector.append(Int32(component))
compDesc.append(Int8(type.utf8[type.utf8.startIndex]))
}
}
private func _convert(_ comp: Bool?, type: String, vector: inout [Int32], compDesc: inout [Int8]) {
if let component = comp {
vector.append(Int32(component ? 0 : 1))
compDesc.append(Int8(type.utf8[type.utf8.startIndex]))
}
}
private func _convert(_ comps: DateComponents) -> (Array<Int32>, Array<Int8>) {
var vector = [Int32]()
var compDesc = [Int8]()
_convert(comps.era, type: "G", vector: &vector, compDesc: &compDesc)
_convert(comps.year, type: "y", vector: &vector, compDesc: &compDesc)
_convert(comps.quarter, type: "Q", vector: &vector, compDesc: &compDesc)
if comps.weekOfYear != NSDateComponentUndefined {
_convert(comps.weekOfYear, type: "w", vector: &vector, compDesc: &compDesc)
} else {
// _convert(comps.week, type: "^", vector: &vector, compDesc: &compDesc)
}
_convert(comps.weekOfMonth, type: "W", vector: &vector, compDesc: &compDesc)
_convert(comps.yearForWeekOfYear, type: "Y", vector: &vector, compDesc: &compDesc)
_convert(comps.weekday, type: "E", vector: &vector, compDesc: &compDesc)
_convert(comps.weekdayOrdinal, type: "F", vector: &vector, compDesc: &compDesc)
_convert(comps.month, type: "M", vector: &vector, compDesc: &compDesc)
_convert(comps.isLeapMonth, type: "l", vector: &vector, compDesc: &compDesc)
_convert(comps.day, type: "d", vector: &vector, compDesc: &compDesc)
_convert(comps.hour, type: "H", vector: &vector, compDesc: &compDesc)
_convert(comps.minute, type: "m", vector: &vector, compDesc: &compDesc)
_convert(comps.second, type: "s", vector: &vector, compDesc: &compDesc)
_convert(comps.nanosecond, type: "#", vector: &vector, compDesc: &compDesc)
compDesc.append(0)
return (vector, compDesc)
}
open func date(from comps: DateComponents) -> Date? {
var (vector, compDesc) = _convert(comps)
self.timeZone = comps.timeZone ?? timeZone
var at: CFAbsoluteTime = 0.0
let res: Bool = withUnsafeMutablePointer(to: &at) { t in
return vector.withUnsafeMutableBufferPointer { (vectorBuffer: inout UnsafeMutableBufferPointer<Int32>) in
return _CFCalendarComposeAbsoluteTimeV(_cfObject, t, compDesc, vectorBuffer.baseAddress!, Int32(vectorBuffer.count))
}
}
if res {
return Date(timeIntervalSinceReferenceDate: at)
} else {
return nil
}
}
private func _setup(_ unitFlags: Unit, field: Unit, type: String, compDesc: inout [Int8]) {
if unitFlags.contains(field) {
compDesc.append(Int8(type.utf8[type.utf8.startIndex]))
}
}
private func _setup(_ unitFlags: Unit) -> [Int8] {
var compDesc = [Int8]()
_setup(unitFlags, field: .era, type: "G", compDesc: &compDesc)
_setup(unitFlags, field: .year, type: "y", compDesc: &compDesc)
_setup(unitFlags, field: .quarter, type: "Q", compDesc: &compDesc)
_setup(unitFlags, field: .month, type: "M", compDesc: &compDesc)
_setup(unitFlags, field: .month, type: "l", compDesc: &compDesc)
_setup(unitFlags, field: .day, type: "d", compDesc: &compDesc)
_setup(unitFlags, field: .weekOfYear, type: "w", compDesc: &compDesc)
_setup(unitFlags, field: .weekOfMonth, type: "W", compDesc: &compDesc)
_setup(unitFlags, field: .yearForWeekOfYear, type: "Y", compDesc: &compDesc)
_setup(unitFlags, field: .weekday, type: "E", compDesc: &compDesc)
_setup(unitFlags, field: .weekdayOrdinal, type: "F", compDesc: &compDesc)
_setup(unitFlags, field: .hour, type: "H", compDesc: &compDesc)
_setup(unitFlags, field: .minute, type: "m", compDesc: &compDesc)
_setup(unitFlags, field: .second, type: "s", compDesc: &compDesc)
_setup(unitFlags, field: .nanosecond, type: "#", compDesc: &compDesc)
compDesc.append(0)
return compDesc
}
private func _setComp(_ unitFlags: Unit, field: Unit, vector: [Int32], compIndex: inout Int, setter: (Int32) -> Void) {
if unitFlags.contains(field) {
if vector[compIndex] != -1 {
setter(vector[compIndex])
}
compIndex += 1
}
}
private func _components(_ unitFlags: Unit, vector: [Int32]) -> DateComponents {
var compIdx = 0
var comps = DateComponents()
_setComp(unitFlags, field: .era, vector: vector, compIndex: &compIdx) { comps.era = Int($0) }
_setComp(unitFlags, field: .year, vector: vector, compIndex: &compIdx) { comps.year = Int($0) }
_setComp(unitFlags, field: .quarter, vector: vector, compIndex: &compIdx) { comps.quarter = Int($0) }
_setComp(unitFlags, field: .month, vector: vector, compIndex: &compIdx) { comps.month = Int($0) }
_setComp(unitFlags, field: .month, vector: vector, compIndex: &compIdx) { comps.isLeapMonth = $0 != 0 }
_setComp(unitFlags, field: .day, vector: vector, compIndex: &compIdx) { comps.day = Int($0) }
_setComp(unitFlags, field: .weekOfYear, vector: vector, compIndex: &compIdx) { comps.weekOfYear = Int($0) }
_setComp(unitFlags, field: .weekOfMonth, vector: vector, compIndex: &compIdx) { comps.weekOfMonth = Int($0) }
_setComp(unitFlags, field: .yearForWeekOfYear, vector: vector, compIndex: &compIdx) { comps.yearForWeekOfYear = Int($0) }
_setComp(unitFlags, field: .weekday, vector: vector, compIndex: &compIdx) { comps.weekday = Int($0) }
_setComp(unitFlags, field: .weekdayOrdinal, vector: vector, compIndex: &compIdx) { comps.weekdayOrdinal = Int($0) }
_setComp(unitFlags, field: .hour, vector: vector, compIndex: &compIdx) { comps.hour = Int($0) }
_setComp(unitFlags, field: .minute, vector: vector, compIndex: &compIdx) { comps.minute = Int($0) }
_setComp(unitFlags, field: .second, vector: vector, compIndex: &compIdx) { comps.second = Int($0) }
_setComp(unitFlags, field: .nanosecond, vector: vector, compIndex: &compIdx) { comps.nanosecond = Int($0) }
if unitFlags.contains(.calendar) {
comps.calendar = self._swiftObject
}
if unitFlags.contains(.timeZone) {
comps.timeZone = timeZone
}
return comps
}
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// The Darwin version is not nullable but this one is since the conversion from the date and unit flags can potentially return nil
open func components(_ unitFlags: Unit, from date: Date) -> DateComponents {
let compDesc = _setup(unitFlags)
// _CFCalendarDecomposeAbsoluteTimeV requires a bit of a funky vector layout; which does not express well in swift; this is the closest I can come up with to the required format
// int32_t ints[20];
// int32_t *vector[20] = {&ints[0], &ints[1], &ints[2], &ints[3], &ints[4], &ints[5], &ints[6], &ints[7], &ints[8], &ints[9], &ints[10], &ints[11], &ints[12], &ints[13], &ints[14], &ints[15], &ints[16], &ints[17], &ints[18], &ints[19]};
var ints = [Int32](repeating: 0, count: 20)
let res = ints.withUnsafeMutableBufferPointer { (intArrayBuffer: inout UnsafeMutableBufferPointer<Int32>) -> Bool in
var vector: [UnsafeMutablePointer<Int32>] = (0..<20).map { idx in
intArrayBuffer.baseAddress!.advanced(by: idx)
}
return vector.withUnsafeMutableBufferPointer { (vecBuffer: inout UnsafeMutableBufferPointer<UnsafeMutablePointer<Int32>>) in
return _CFCalendarDecomposeAbsoluteTimeV(_cfObject, date.timeIntervalSinceReferenceDate, compDesc, vecBuffer.baseAddress!, Int32(compDesc.count - 1))
}
}
if res {
return _components(unitFlags, vector: ints)
}
fatalError()
}
open func date(byAdding comps: DateComponents, to date: Date, options opts: Options = []) -> Date? {
var (vector, compDesc) = _convert(comps)
var at: CFAbsoluteTime = date.timeIntervalSinceReferenceDate
let res: Bool = withUnsafeMutablePointer(to: &at) { t in
let count = Int32(vector.count)
return vector.withUnsafeMutableBufferPointer { (vectorBuffer: inout UnsafeMutableBufferPointer<Int32>) in
return _CFCalendarAddComponentsV(_cfObject, t, CFOptionFlags(opts.rawValue), compDesc, vectorBuffer.baseAddress!, count)
}
}
if res {
return Date(timeIntervalSinceReferenceDate: at)
}
return nil
}
open func components(_ unitFlags: Unit, from startingDate: Date, to resultDate: Date, options opts: Options = []) -> DateComponents {
let compDesc = _setup(unitFlags)
var ints = [Int32](repeating: 0, count: 20)
let res = ints.withUnsafeMutableBufferPointer { (intArrayBuffer: inout UnsafeMutableBufferPointer<Int32>) -> Bool in
var vector: [UnsafeMutablePointer<Int32>] = (0..<20).map { idx in
return intArrayBuffer.baseAddress!.advanced(by: idx)
}
let count = Int32(vector.count)
return vector.withUnsafeMutableBufferPointer { (vecBuffer: inout UnsafeMutableBufferPointer<UnsafeMutablePointer<Int32>>) in
return _CFCalendarGetComponentDifferenceV(_cfObject, startingDate.timeIntervalSinceReferenceDate, resultDate.timeIntervalSinceReferenceDate, CFOptionFlags(opts.rawValue), compDesc, vecBuffer.baseAddress!, count)
}
}
if res {
return _components(unitFlags, vector: ints)
}
fatalError()
}
/*
This API is a convenience for getting era, year, month, and day of a given date.
Pass NULL for a NSInteger pointer parameter if you don't care about that value.
*/
open func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, year yearValuePointer: UnsafeMutablePointer<Int>?, month monthValuePointer: UnsafeMutablePointer<Int>?, day dayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) {
let comps = components([.era, .year, .month, .day], from: date)
if let value = comps.era {
eraValuePointer?.pointee = value
} else {
eraValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.year {
yearValuePointer?.pointee = value
} else {
yearValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.month {
monthValuePointer?.pointee = value
} else {
monthValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.day {
dayValuePointer?.pointee = value
} else {
dayValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.year {
yearValuePointer?.pointee = value
} else {
yearValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.month {
monthValuePointer?.pointee = value
} else {
monthValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.day {
dayValuePointer?.pointee = value
} else {
dayValuePointer?.pointee = NSDateComponentUndefined
}
}
/*
This API is a convenience for getting era, year for week-of-year calculations, week of year, and weekday of a given date.
Pass NULL for a NSInteger pointer parameter if you don't care about that value.
*/
open func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, yearForWeekOfYear yearValuePointer: UnsafeMutablePointer<Int>?, weekOfYear weekValuePointer: UnsafeMutablePointer<Int>?, weekday weekdayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) {
let comps = components([.era, .yearForWeekOfYear, .weekOfYear, .weekday], from: date)
if let value = comps.era {
eraValuePointer?.pointee = value
} else {
eraValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.yearForWeekOfYear {
yearValuePointer?.pointee = value
} else {
yearValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.weekOfYear {
weekValuePointer?.pointee = value
} else {
weekValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.weekday {
weekdayValuePointer?.pointee = value
} else {
weekdayValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.yearForWeekOfYear {
yearValuePointer?.pointee = value
} else {
yearValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.weekOfYear {
weekValuePointer?.pointee = value
} else {
weekValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.weekday {
weekdayValuePointer?.pointee = value
} else {
weekdayValuePointer?.pointee = NSDateComponentUndefined
}
}
/*
This API is a convenience for getting hour, minute, second, and nanoseconds of a given date.
Pass NULL for a NSInteger pointer parameter if you don't care about that value.
*/
open func getHour(_ hourValuePointer: UnsafeMutablePointer<Int>?, minute minuteValuePointer: UnsafeMutablePointer<Int>?, second secondValuePointer: UnsafeMutablePointer<Int>?, nanosecond nanosecondValuePointer: UnsafeMutablePointer<Int>?, from date: Date) {
let comps = components([.hour, .minute, .second, .nanosecond], from: date)
if let value = comps.hour {
hourValuePointer?.pointee = value
} else {
hourValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.minute {
minuteValuePointer?.pointee = value
} else {
minuteValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.second {
secondValuePointer?.pointee = value
} else {
secondValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.nanosecond {
nanosecondValuePointer?.pointee = value
} else {
nanosecondValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.minute {
minuteValuePointer?.pointee = value
} else {
minuteValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.second {
secondValuePointer?.pointee = value
} else {
secondValuePointer?.pointee = NSDateComponentUndefined
}
if let value = comps.nanosecond {
nanosecondValuePointer?.pointee = value
} else {
nanosecondValuePointer?.pointee = NSDateComponentUndefined
}
}
/*
Get just one component's value.
*/
open func component(_ unit: Unit, from date: Date) -> Int {
let comps = components(unit, from: date)
if let res = comps.value(for: Calendar._fromCalendarUnit(unit)) {
return res
} else {
return NSDateComponentUndefined
}
}
/*
Create a date with given components.
Current era is assumed.
*/
open func date(era eraValue: Int, year yearValue: Int, month monthValue: Int, day dayValue: Int, hour hourValue: Int, minute minuteValue: Int, second secondValue: Int, nanosecond nanosecondValue: Int) -> Date? {
var comps = DateComponents()
comps.era = eraValue
comps.year = yearValue
comps.month = monthValue
comps.day = dayValue
comps.hour = hourValue
comps.minute = minuteValue
comps.second = secondValue
comps.nanosecond = nanosecondValue
return date(from: comps)
}
/*
Create a date with given components.
Current era is assumed.
*/
open func date(era eraValue: Int, yearForWeekOfYear yearValue: Int, weekOfYear weekValue: Int, weekday weekdayValue: Int, hour hourValue: Int, minute minuteValue: Int, second secondValue: Int, nanosecond nanosecondValue: Int) -> Date? {
var comps = DateComponents()
comps.era = eraValue
comps.yearForWeekOfYear = yearValue
comps.weekOfYear = weekValue
comps.weekday = weekdayValue
comps.hour = hourValue
comps.minute = minuteValue
comps.second = secondValue
comps.nanosecond = nanosecondValue
return date(from: comps)
}
/*
This API returns the first moment date of a given date.
Pass in [NSDate date], for example, if you want the start of "today".
If there were two midnights, it returns the first. If there was none, it returns the first moment that did exist.
*/
open func startOfDay(for date: Date) -> Date {
return range(of: .day, for: date)!.start
}
/*
This API returns all the date components of a date, as if in a given time zone (instead of the receiving calendar's time zone).
The time zone overrides the time zone of the NSCalendar for the purposes of this calculation.
Note: if you want "date information in a given time zone" in order to display it, you should use NSDateFormatter to format the date.
*/
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// The Darwin version is not nullable but this one is since the conversion from the date and unit flags can potentially return nil
open func components(in timezone: TimeZone, from date: Date) -> DateComponents {
let oldTz = self.timeZone
self.timeZone = timezone
let comps = components([.era, .year, .month, .day, .hour, .minute, .second, .nanosecond, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear, .calendar, .timeZone], from: date)
self.timeZone = oldTz
return comps
}
/*
This API compares the given dates down to the given unit, reporting them equal if they are the same in the given unit and all larger units, otherwise either less than or greater than.
*/
open func compare(_ date1: Date, to date2: Date, toUnitGranularity unit: Unit) -> ComparisonResult {
switch (unit) {
case Unit.calendar:
return .orderedSame
case Unit.timeZone:
return .orderedSame
case Unit.day:
fallthrough
case Unit.hour:
let range = self.range(of: unit, for: date1)
let ats = range!.start.timeIntervalSinceReferenceDate
let at2 = date2.timeIntervalSinceReferenceDate
if ats <= at2 && at2 < ats + range!.duration {
return .orderedSame
}
if at2 < ats {
return .orderedDescending
}
return .orderedAscending
case Unit.minute:
var int1 = 0.0
var int2 = 0.0
modf(date1.timeIntervalSinceReferenceDate, &int1)
modf(date2.timeIntervalSinceReferenceDate, &int2)
int1 = floor(int1 / 60.0)
int2 = floor(int2 / 60.0)
if int1 == int2 {
return .orderedSame
}
if int2 < int1 {
return .orderedDescending
}
return .orderedAscending
case Unit.second:
var int1 = 0.0
var int2 = 0.0
modf(date1.timeIntervalSinceReferenceDate, &int1)
modf(date2.timeIntervalSinceReferenceDate, &int2)
if int1 == int2 {
return .orderedSame
}
if int2 < int1 {
return .orderedDescending
}
return .orderedAscending
case Unit.nanosecond:
var int1 = 0.0
var int2 = 0.0
let frac1 = modf(date1.timeIntervalSinceReferenceDate, &int1)
let frac2 = modf(date2.timeIntervalSinceReferenceDate, &int2)
int1 = floor(frac1 * 1000000000.0)
int2 = floor(frac2 * 1000000000.0)
if int1 == int2 {
return .orderedSame
}
if int2 < int1 {
return .orderedDescending
}
return .orderedAscending
default:
break
}
let calendarUnits1: [Unit] = [.era, .year, .month, .day]
let calendarUnits2: [Unit] = [.era, .year, .month, .weekdayOrdinal, .day]
let calendarUnits3: [Unit] = [.era, .year, .month, .weekOfMonth, .weekday]
let calendarUnits4: [Unit] = [.era, .yearForWeekOfYear, .weekOfYear, .weekday]
var units: [Unit]
if unit == .yearForWeekOfYear || unit == .weekOfYear {
units = calendarUnits4
} else if unit == .weekdayOrdinal {
units = calendarUnits2
} else if unit == .weekday || unit == .weekOfMonth {
units = calendarUnits3
} else {
units = calendarUnits1
}
// TODO: verify that the return value here is never going to be nil; it seems like it may - thusly making the return value here optional which would result in sadness and regret
let reducedUnits = units.reduce(Unit()) { $0.union($1) }
let comp1 = components(reducedUnits, from: date1)
let comp2 = components(reducedUnits, from: date2)
for unit in units {
let value1 = comp1.value(for: Calendar._fromCalendarUnit(unit))
let value2 = comp2.value(for: Calendar._fromCalendarUnit(unit))
if value1! > value2! {
return .orderedDescending
} else if value1! < value2! {
return .orderedAscending
}
if unit == .month && calendarIdentifier == .chinese {
if let leap1 = comp1.isLeapMonth {
if let leap2 = comp2.isLeapMonth {
if !leap1 && leap2 {
return .orderedAscending
} else if leap1 && !leap2 {
return .orderedDescending
}
}
}
}
if unit == reducedUnits {
return .orderedSame
}
}
return .orderedSame
}
/*
This API compares the given dates down to the given unit, reporting them equal if they are the same in the given unit and all larger units.
*/
open func isDate(_ date1: Date, equalTo date2: Date, toUnitGranularity unit: Unit) -> Bool {
return compare(date1, to: date2, toUnitGranularity: unit) == .orderedSame
}
/*
This API compares the Days of the given dates, reporting them equal if they are in the same Day.
*/
open func isDate(_ date1: Date, inSameDayAs date2: Date) -> Bool {
return compare(date1, to: date2, toUnitGranularity: .day) == .orderedSame
}
/*
This API reports if the date is within "today".
*/
open func isDateInToday(_ date: Date) -> Bool {
return compare(date, to: Date(), toUnitGranularity: .day) == .orderedSame
}
/*
This API reports if the date is within "yesterday".
*/
open func isDateInYesterday(_ date: Date) -> Bool {
if let interval = range(of: .day, for: Date()) {
let inYesterday = interval.start - 60.0
return compare(date, to: inYesterday, toUnitGranularity: .day) == .orderedSame
} else {
return false
}
}
/*
This API reports if the date is within "tomorrow".
*/
open func isDateInTomorrow(_ date: Date) -> Bool {
if let interval = range(of: .day, for: Date()) {
let inTomorrow = interval.end + 60.0
return compare(date, to: inTomorrow, toUnitGranularity: .day) == .orderedSame
} else {
return false
}
}
/*
This API reports if the date is within a weekend period, as defined by the calendar and calendar's locale.
*/
open func isDateInWeekend(_ date: Date) -> Bool {
return _CFCalendarIsWeekend(_cfObject, date.timeIntervalSince1970)
}
/// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer.
/// The current exposed API in Foundation on Darwin platforms is:
/// open func rangeOfWeekendStartDate(_ datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, containingDate date: NSDate) -> Bool
/// which is not implementable on Linux due to the lack of being able to properly implement AutoreleasingUnsafeMutablePointer.
/// Find the range of the weekend around the given date, returned via two by-reference parameters.
/// Returns nil if the given date is not in a weekend.
/// - Note: A given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a Day in some calendars and locales.
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func range(ofWeekendContaining date: Date) -> DateInterval? {
if let next = nextWeekendAfter(date, options: []) {
if let prev = nextWeekendAfter(next.start, options: .searchBackwards) {
if prev.start.timeIntervalSinceReferenceDate <= date.timeIntervalSinceReferenceDate && date.timeIntervalSinceReferenceDate <= prev.end.timeIntervalSinceReferenceDate {
return prev
}
}
}
return nil
}
/// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer.
/// The current exposed API in Foundation on Darwin platforms is:
/// open func nextWeekendStartDate(_ datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, options: Options, afterDate date: NSDate) -> Bool
/// Returns the range of the next weekend, via two by-reference parameters, which starts strictly after the given date.
/// The .SearchBackwards option can be used to find the previous weekend range strictly before the date.
/// Returns nil if there are no such things as weekend in the calendar and its locale.
/// - Note: A given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a Day in some calendars and locales.
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func nextWeekendAfter(_ date: Date, options: Options) -> DateInterval? {
var range = _CFCalendarWeekendRange()
let res = withUnsafeMutablePointer(to: &range) { rangep in
return _CFCalendarGetNextWeekend(_cfObject, rangep)
}
if res {
var comp = DateComponents()
comp.weekday = range.start
if let nextStart = nextDate(after: date, matching: comp, options: options.union(.matchNextTime)) {
let start = nextStart + range.onsetTime
comp.weekday = range.end
if let nextEnd = nextDate(after: date, matching: comp, options: options.union(.matchNextTime)) {
var end = nextEnd
if end.compare(start) == .orderedAscending {
if let nextOrderedEnd = nextDate(after: end, matching: comp, options: options.union(.matchNextTime)) {
end = nextOrderedEnd
} else {
return nil
}
}
if range.ceaseTime > 0 {
end = end + range.ceaseTime
} else {
if let dayEnd = self.range(of: .day, for: end) {
end = startOfDay(for: dayEnd.end)
} else {
return nil
}
}
return DateInterval(start: start, end: end)
}
}
}
return nil
}
/*
This API returns the difference between two dates specified as date components.
For units which are not specified in each NSDateComponents, but required to specify an absolute date, the base value of the unit is assumed. For example, for an NSDateComponents with just a Year and a Month specified, a Day of 1, and an Hour, Minute, Second, and Nanosecond of 0 are assumed.
Calendrical calculations with unspecified Year or Year value prior to the start of a calendar are not advised.
For each date components object, if its time zone property is set, that time zone is used for it; if the calendar property is set, that is used rather than the receiving calendar, and if both the calendar and time zone are set, the time zone property value overrides the time zone of the calendar property.
No options are currently defined; pass 0.
*/
open func components(_ unitFlags: Unit, from startingDateComp: DateComponents, to resultDateComp: DateComponents, options: Options = []) -> DateComponents {
var startDate: Date?
var toDate: Date?
if let startCalendar = startingDateComp.calendar {
startDate = startCalendar.date(from: startingDateComp)
} else {
startDate = date(from: startingDateComp)
}
if let toCalendar = resultDateComp.calendar {
toDate = toCalendar.date(from: resultDateComp)
} else {
toDate = date(from: resultDateComp)
}
if let start = startDate {
if let end = toDate {
return components(unitFlags, from: start, to: end, options: options)
}
}
fatalError()
}
/*
This API returns a new NSDate object representing the date calculated by adding an amount of a specific component to a given date.
The NSCalendarWrapComponents option specifies if the component should be incremented and wrap around to zero/one on overflow, and should not cause higher units to be incremented.
*/
open func date(byAdding unit: Unit, value: Int, to date: Date, options: Options = []) -> Date? {
var comps = DateComponents()
comps.setValue(value, for: Calendar._fromCalendarUnit(unit))
return self.date(byAdding: comps, to: date, options: options)
}
/*
This method computes the dates which match (or most closely match) a given set of components, and calls the block once for each of them, until the enumeration is stopped.
There will be at least one intervening date which does not match all the components (or the given date itself must not match) between the given date and any result.
If the NSCalendarSearchBackwards option is used, this method finds the previous match before the given date. The intent is that the same matches as for a forwards search will be found (that is, if you are enumerating forwards or backwards for each hour with minute "27", the seconds in the date you will get in forwards search would obviously be 00, and the same will be true in a backwards search in order to implement this rule. Similarly for DST backwards jumps which repeats times, you'll get the first match by default, where "first" is defined from the point of view of searching forwards. So, when searching backwards looking for a particular hour, with no minute and second specified, you don't get a minute and second of 59:59 for the matching hour (which would be the nominal first match within a given hour, given the other rules here, when searching backwards).
If the NSCalendarMatchStrictly option is used, the algorithm travels as far forward or backward as necessary looking for a match, but there are ultimately implementation-defined limits in how far distant the search will go. If the NSCalendarMatchStrictly option is not specified, the algorithm searches up to the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument. If you want to find the next Feb 29 in the Gregorian calendar, for example, you have to specify the NSCalendarMatchStrictly option to guarantee finding it.
If an exact match is not possible, and requested with the NSCalendarMatchStrictly option, nil is passed to the block and the enumeration ends. (Logically, since an exact match searches indefinitely into the future, if no match is found there's no point in continuing the enumeration.)
If the NSCalendarMatchStrictly option is NOT used, exactly one option from the set {NSCalendarMatchPreviousTimePreservingSmallerUnits, NSCalendarMatchNextTimePreservingSmallerUnits, NSCalendarMatchNextTime} must be specified, or an illegal argument exception will be thrown.
If the NSCalendarMatchPreviousTimePreservingSmallerUnits option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the previous existing value of the missing unit and preserves the lower units' values (e.g., no 2:37am results in 1:37am, if that exists).
If the NSCalendarMatchNextTimePreservingSmallerUnits option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the next existing value of the missing unit and preserves the lower units' values (e.g., no 2:37am results in 3:37am, if that exists).
If the NSCalendarMatchNextTime option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the next existing time which exists (e.g., no 2:37am results in 3:00am, if that exists).
If the NSCalendarMatchFirst option is specified, and there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the first occurrence.
If the NSCalendarMatchLast option is specified, and there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the last occurrence.
If neither the NSCalendarMatchFirst or NSCalendarMatchLast option is specified, the default behavior is to act as if NSCalendarMatchFirst was specified.
There is no option to return middle occurrences of more than two occurrences of a matching time, if such exist.
Result dates have an integer number of seconds (as if 0 was specified for the nanoseconds property of the NSDateComponents matching parameter), unless a value was set in the nanoseconds property, in which case the result date will have that number of nanoseconds (or as close as possible with floating point numbers).
The enumeration is stopped by setting *stop = YES in the block and return. It is not necessary to set *stop to NO to keep the enumeration going.
*/
open func enumerateDates(startingAfter start: Date, matching comps: DateComponents, options opts: NSCalendar.Options = [], using block: (Date?, Bool, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
NSUnimplemented()
}
/*
This method computes the next date which matches (or most closely matches) a given set of components.
The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above.
To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result.
*/
open func nextDate(after date: Date, matching comps: DateComponents, options: Options = []) -> Date? {
var result: Date?
enumerateDates(startingAfter: date, matching: comps, options: options) { date, exactMatch, stop in
result = date
stop.pointee = true
}
return result
}
/*
This API returns a new NSDate object representing the date found which matches a specific component value.
The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above.
To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result.
*/
open func nextDate(after date: Date, matching unit: Unit, value: Int, options: Options = []) -> Date? {
var comps = DateComponents()
comps.setValue(value, for: Calendar._fromCalendarUnit(unit))
return nextDate(after:date, matching: comps, options: options)
}
/*
This API returns a new NSDate object representing the date found which matches the given hour, minute, and second values.
The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above.
To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result.
*/
open func nextDate(after date: Date, matchingHour hourValue: Int, minute minuteValue: Int, second secondValue: Int, options: Options = []) -> Date? {
var comps = DateComponents()
comps.hour = hourValue
comps.minute = minuteValue
comps.second = secondValue
return nextDate(after: date, matching: comps, options: options)
}
/*
This API returns a new NSDate object representing the date calculated by setting a specific component to a given time, and trying to keep lower components the same. If the unit already has that value, this may result in a date which is the same as the given date.
Changing a component's value often will require higher or coupled components to change as well. For example, setting the Weekday to Thursday usually will require the Day component to change its value, and possibly the Month and Year as well.
If no such time exists, the next available time is returned (which could, for example, be in a different day, week, month, ... than the nominal target date). Setting a component to something which would be inconsistent forces other units to change; for example, setting the Weekday to Thursday probably shifts the Day and possibly Month and Year.
The specific behaviors here are as yet unspecified; for example, if I change the weekday to Thursday, does that move forward to the next, backward to the previous, or to the nearest Thursday? A likely rule is that the algorithm will try to produce a result which is in the next-larger unit to the one given (there's a table of this mapping at the top of this document). So for the "set to Thursday" example, find the Thursday in the Week in which the given date resides (which could be a forwards or backwards move, and not necessarily the nearest Thursday). For forwards or backwards behavior, one can use the -nextDateAfterDate:matchingUnit:value:options: method above.
*/
open func date(bySettingUnit unit: Unit, value v: Int, of date: Date, options opts: Options = []) -> Date? {
let currentValue = component(unit, from: date)
if currentValue == v {
return date
}
var targetComp = DateComponents()
targetComp.setValue(v, for: Calendar._fromCalendarUnit(unit))
var result: Date?
enumerateDates(startingAfter: date, matching: targetComp, options: .matchNextTime) { date, match, stop in
result = date
stop.pointee = true
}
return result
}
/*
This API returns a new NSDate object representing the date calculated by setting hour, minute, and second to a given time.
If no such time exists, the next available time is returned (which could, for example, be in a different day than the nominal target date).
The intent is to return a date on the same day as the original date argument. This may result in a date which is earlier than the given date, of course.
*/
open func date(bySettingHour h: Int, minute m: Int, second s: Int, of date: Date, options opts: Options = []) -> Date? {
if let range = range(of: .day, for: date) {
var comps = DateComponents()
comps.hour = h
comps.minute = m
comps.second = s
var options: Options = .matchNextTime
options.formUnion(opts.contains(.matchLast) ? .matchLast : .matchFirst)
if opts.contains(.matchStrictly) {
options.formUnion(.matchStrictly)
}
if let result = nextDate(after: range.start - 0.5, matching: comps, options: options) {
if result.compare(range.start) == .orderedAscending {
return nextDate(after: range.start, matching: comps, options: options)
}
return result
}
}
return nil
}
/*
This API returns YES if the date has all the matched components. Otherwise, it returns NO.
It is useful to test the return value of the -nextDateAfterDate:matchingUnit:value:options:, to find out if the components were obeyed or if the method had to fudge the result value due to missing time.
*/
open func date(_ date: Date, matchesComponents components: DateComponents) -> Bool {
let units: [Unit] = [.era, .year, .month, .day, .hour, .minute, .second, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear, .nanosecond]
var unitFlags: Unit = []
for unit in units {
if components.value(for: Calendar._fromCalendarUnit(unit)) != NSDateComponentUndefined {
unitFlags.formUnion(unit)
}
}
if unitFlags == [] {
if components.isLeapMonth != nil {
let comp = self.components(.month, from: date)
if let leap = comp.isLeapMonth {
return leap
}
return false
}
}
let comp = self.components(unitFlags, from: date)
var compareComp = comp
var tempComp = components
tempComp.isLeapMonth = comp.isLeapMonth
if let nanosecond = comp.value(for: .nanosecond) {
if labs(nanosecond - tempComp.value(for: .nanosecond)!) > 500 {
return false
} else {
compareComp.nanosecond = 0
tempComp.nanosecond = 0
}
return tempComp == compareComp
}
return false
}
}
// This notification is posted through [NSNotificationCenter defaultCenter]
// when the system day changes. Register with "nil" as the object of this
// notification. If the computer/device is asleep when the day changed,
// this will be posted on wakeup. You'll get just one of these if the
// machine has been asleep for several days. The definition of "Day" is
// relative to the current calendar ([NSCalendar currentCalendar]) of the
// process and its locale and time zone. There are no guarantees that this
// notification is received by observers in a "timely" manner, same as
// with distributed notifications.
extension NSNotification.Name {
public static let NSCalendarDayChanged = NSNotification.Name(rawValue: "NSCalendarDayChangedNotification")
}
// This is a just used as an extensible struct, basically;
// note that there are two uses: one for specifying a date
// via components (some components may be missing, making the
// specific date ambiguous), and the other for specifying a
// set of component quantities (like, 3 months and 5 hours).
// Undefined fields have (or fields can be set to) the value
// NSDateComponentUndefined.
// NSDateComponents is not responsible for answering questions
// about a date beyond the information it has been initialized
// with; for example, if you initialize one with May 6, 2004,
// and then ask for the weekday, you'll get Undefined, not Thurs.
// A NSDateComponents is meaningless in itself, because you need
// to know what calendar it is interpreted against, and you need
// to know whether the values are absolute values of the units,
// or quantities of the units.
// When you create a new one of these, all values begin Undefined.
public var NSDateComponentUndefined: Int = Int.max
open class NSDateComponents : NSObject, NSCopying, NSSecureCoding {
internal var _calendar: Calendar?
internal var _timeZone: TimeZone?
internal var _values = [Int](repeating: NSDateComponentUndefined, count: 19)
public override init() {
super.init()
}
open override var hash: Int {
var calHash = 0
if let cal = calendar {
calHash = cal.hashValue
}
if let tz = timeZone {
calHash ^= tz.hashValue
}
var y = year
if NSDateComponentUndefined == y {
y = 0
}
var m = month
if NSDateComponentUndefined == m {
m = 0
}
var d = day
if NSDateComponentUndefined == d {
d = 0
}
var h = hour
if NSDateComponentUndefined == h {
h = 0
}
var mm = minute
if NSDateComponentUndefined == mm {
mm = 0
}
var s = second
if NSDateComponentUndefined == s {
s = 0
}
var yy = yearForWeekOfYear
if NSDateComponentUndefined == yy {
yy = 0
}
return calHash + (32832013 * (y + yy) + 2678437 * m + 86413 * d + 3607 * h + 61 * mm + s) + (41 * weekOfYear + 11 * weekOfMonth + 7 * weekday + 3 * weekdayOrdinal + quarter) * (1 << 5)
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSDateComponents else { return false }
return self === other
|| (era == other.era
&& year == other.year
&& quarter == other.quarter
&& month == other.month
&& day == other.day
&& hour == other.hour
&& minute == other.minute
&& second == other.second
&& nanosecond == other.nanosecond
&& weekOfYear == other.weekOfYear
&& weekOfMonth == other.weekOfMonth
&& yearForWeekOfYear == other.yearForWeekOfYear
&& weekday == other.weekday
&& weekdayOrdinal == other.weekdayOrdinal
&& isLeapMonth == other.isLeapMonth
&& calendar == other.calendar
&& timeZone == other.timeZone)
}
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
self.init()
self.era = aDecoder.decodeInteger(forKey: "NS.era")
self.year = aDecoder.decodeInteger(forKey: "NS.year")
self.quarter = aDecoder.decodeInteger(forKey: "NS.quarter")
self.month = aDecoder.decodeInteger(forKey: "NS.month")
self.day = aDecoder.decodeInteger(forKey: "NS.day")
self.hour = aDecoder.decodeInteger(forKey: "NS.hour")
self.minute = aDecoder.decodeInteger(forKey: "NS.minute")
self.second = aDecoder.decodeInteger(forKey: "NS.second")
self.nanosecond = aDecoder.decodeInteger(forKey: "NS.nanosec")
self.weekOfYear = aDecoder.decodeInteger(forKey: "NS.weekOfYear")
self.weekOfMonth = aDecoder.decodeInteger(forKey: "NS.weekOfMonth")
self.yearForWeekOfYear = aDecoder.decodeInteger(forKey: "NS.yearForWOY")
self.weekday = aDecoder.decodeInteger(forKey: "NS.weekday")
self.weekdayOrdinal = aDecoder.decodeInteger(forKey: "NS.weekdayOrdinal")
self.isLeapMonth = aDecoder.decodeBool(forKey: "NS.isLeapMonth")
self.calendar = aDecoder.decodeObject(of: NSCalendar.self, forKey: "NS.calendar")?._swiftObject
self.timeZone = aDecoder.decodeObject(of: NSTimeZone.self, forKey: "NS.timezone")?._swiftObject
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.era, forKey: "NS.era")
aCoder.encode(self.year, forKey: "NS.year")
aCoder.encode(self.quarter, forKey: "NS.quarter")
aCoder.encode(self.month, forKey: "NS.month")
aCoder.encode(self.day, forKey: "NS.day")
aCoder.encode(self.hour, forKey: "NS.hour")
aCoder.encode(self.minute, forKey: "NS.minute")
aCoder.encode(self.second, forKey: "NS.second")
aCoder.encode(self.nanosecond, forKey: "NS.nanosec")
aCoder.encode(self.weekOfYear, forKey: "NS.weekOfYear")
aCoder.encode(self.weekOfMonth, forKey: "NS.weekOfMonth")
aCoder.encode(self.yearForWeekOfYear, forKey: "NS.yearForWOY")
aCoder.encode(self.weekday, forKey: "NS.weekday")
aCoder.encode(self.weekdayOrdinal, forKey: "NS.weekdayOrdinal")
aCoder.encode(self.isLeapMonth, forKey: "NS.isLeapMonth")
aCoder.encode(self.calendar?._nsObject, forKey: "NS.calendar")
aCoder.encode(self.timeZone?._nsObject, forKey: "NS.timezone")
}
static public var supportsSecureCoding: Bool {
return true
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
let newObj = NSDateComponents()
newObj.calendar = calendar
newObj.timeZone = timeZone
newObj.era = era
newObj.year = year
newObj.month = month
newObj.day = day
newObj.hour = hour
newObj.minute = minute
newObj.second = second
newObj.nanosecond = nanosecond
newObj.weekOfYear = weekOfYear
newObj.weekOfMonth = weekOfMonth
newObj.yearForWeekOfYear = yearForWeekOfYear
newObj.weekday = weekday
newObj.weekdayOrdinal = weekdayOrdinal
newObj.quarter = quarter
if leapMonthSet {
newObj.isLeapMonth = isLeapMonth
}
return newObj
}
/*@NSCopying*/ open var calendar: Calendar? {
get {
return _calendar
}
set {
if let val = newValue {
_calendar = val
} else {
_calendar = nil
}
}
}
/*@NSCopying*/ open var timeZone: TimeZone?
open var era: Int {
get {
return _values[0]
}
set {
_values[0] = newValue
}
}
open var year: Int {
get {
return _values[1]
}
set {
_values[1] = newValue
}
}
open var month: Int {
get {
return _values[2]
}
set {
_values[2] = newValue
}
}
open var day: Int {
get {
return _values[3]
}
set {
_values[3] = newValue
}
}
open var hour: Int {
get {
return _values[4]
}
set {
_values[4] = newValue
}
}
open var minute: Int {
get {
return _values[5]
}
set {
_values[5] = newValue
}
}
open var second: Int {
get {
return _values[6]
}
set {
_values[6] = newValue
}
}
open var weekday: Int {
get {
return _values[8]
}
set {
_values[8] = newValue
}
}
open var weekdayOrdinal: Int {
get {
return _values[9]
}
set {
_values[9] = newValue
}
}
open var quarter: Int {
get {
return _values[10]
}
set {
_values[10] = newValue
}
}
open var nanosecond: Int {
get {
return _values[11]
}
set {
_values[11] = newValue
}
}
open var weekOfYear: Int {
get {
return _values[12]
}
set {
_values[12] = newValue
}
}
open var weekOfMonth: Int {
get {
return _values[13]
}
set {
_values[13] = newValue
}
}
open var yearForWeekOfYear: Int {
get {
return _values[14]
}
set {
_values[14] = newValue
}
}
open var isLeapMonth: Bool {
get {
return _values[15] == 1
}
set {
_values[15] = newValue ? 1 : 0
}
}
internal var leapMonthSet: Bool {
return _values[15] != NSDateComponentUndefined
}
/*@NSCopying*/ open var date: Date? {
if let tz = timeZone {
calendar?.timeZone = tz
}
return calendar?.date(from: self._swiftObject)
}
/*
This API allows one to set a specific component of NSDateComponents, by enum constant value rather than property name.
The calendar and timeZone and isLeapMonth properties cannot be set by this method.
*/
open func setValue(_ value: Int, forComponent unit: NSCalendar.Unit) {
switch unit {
case NSCalendar.Unit.era:
era = value
case NSCalendar.Unit.year:
year = value
case NSCalendar.Unit.month:
month = value
case NSCalendar.Unit.day:
day = value
case NSCalendar.Unit.hour:
hour = value
case NSCalendar.Unit.minute:
minute = value
case NSCalendar.Unit.second:
second = value
case NSCalendar.Unit.nanosecond:
nanosecond = value
case NSCalendar.Unit.weekday:
weekday = value
case NSCalendar.Unit.weekdayOrdinal:
weekdayOrdinal = value
case NSCalendar.Unit.quarter:
quarter = value
case NSCalendar.Unit.weekOfMonth:
weekOfMonth = value
case NSCalendar.Unit.weekOfYear:
weekOfYear = value
case NSCalendar.Unit.yearForWeekOfYear:
yearForWeekOfYear = value
case NSCalendar.Unit.calendar:
print(".Calendar cannot be set via \(#function)")
case NSCalendar.Unit.timeZone:
print(".TimeZone cannot be set via \(#function)")
default:
break
}
}
/*
This API allows one to get the value of a specific component of NSDateComponents, by enum constant value rather than property name.
The calendar and timeZone and isLeapMonth property values cannot be gotten by this method.
*/
open func value(forComponent unit: NSCalendar.Unit) -> Int {
switch unit {
case NSCalendar.Unit.era:
return era
case NSCalendar.Unit.year:
return year
case NSCalendar.Unit.month:
return month
case NSCalendar.Unit.day:
return day
case NSCalendar.Unit.hour:
return hour
case NSCalendar.Unit.minute:
return minute
case NSCalendar.Unit.second:
return second
case NSCalendar.Unit.nanosecond:
return nanosecond
case NSCalendar.Unit.weekday:
return weekday
case NSCalendar.Unit.weekdayOrdinal:
return weekdayOrdinal
case NSCalendar.Unit.quarter:
return quarter
case NSCalendar.Unit.weekOfMonth:
return weekOfMonth
case NSCalendar.Unit.weekOfYear:
return weekOfYear
case NSCalendar.Unit.yearForWeekOfYear:
return yearForWeekOfYear
default:
break
}
return NSDateComponentUndefined
}
/*
Reports whether or not the combination of properties which have been set in the receiver is a date which exists in the calendar.
This method is not appropriate for use on NSDateComponents objects which are specifying relative quantities of calendar components.
Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap.
If the time zone property is set in the NSDateComponents object, it is used.
The calendar property must be set, or NO is returned.
*/
open var isValidDate: Bool {
if let cal = calendar {
return isValidDate(in: cal)
}
return false
}
/*
Reports whether or not the combination of properties which have been set in the receiver is a date which exists in the calendar.
This method is not appropriate for use on NSDateComponents objects which are specifying relative quantities of calendar components.
Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap.
If the time zone property is set in the NSDateComponents object, it is used.
*/
open func isValidDate(in calendar: Calendar) -> Bool {
var cal = calendar
if let tz = timeZone {
cal.timeZone = tz
}
let ns = nanosecond
if ns != NSDateComponentUndefined && 1000 * 1000 * 1000 <= ns {
return false
}
if ns != NSDateComponentUndefined && 0 < ns {
nanosecond = 0
}
let d = calendar.date(from: self._swiftObject)
if ns != NSDateComponentUndefined && 0 < ns {
nanosecond = ns
}
if let date = d {
let all: NSCalendar.Unit = [.era, .year, .month, .day, .hour, .minute, .second, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear]
let comps = calendar._bridgeToObjectiveC().components(all, from: date)
var val = era
if val != NSDateComponentUndefined {
if comps.era != val {
return false
}
}
val = year
if val != NSDateComponentUndefined {
if comps.year != val {
return false
}
}
val = month
if val != NSDateComponentUndefined {
if comps.month != val {
return false
}
}
if leapMonthSet {
if comps.isLeapMonth != isLeapMonth {
return false
}
}
val = day
if val != NSDateComponentUndefined {
if comps.day != val {
return false
}
}
val = hour
if val != NSDateComponentUndefined {
if comps.hour != val {
return false
}
}
val = minute
if val != NSDateComponentUndefined {
if comps.minute != val {
return false
}
}
val = second
if val != NSDateComponentUndefined {
if comps.second != val {
return false
}
}
val = weekday
if val != NSDateComponentUndefined {
if comps.weekday != val {
return false
}
}
val = weekdayOrdinal
if val != NSDateComponentUndefined {
if comps.weekdayOrdinal != val {
return false
}
}
val = quarter
if val != NSDateComponentUndefined {
if comps.quarter != val {
return false
}
}
val = weekOfMonth
if val != NSDateComponentUndefined {
if comps.weekOfMonth != val {
return false
}
}
val = weekOfYear
if val != NSDateComponentUndefined {
if comps.weekOfYear != val {
return false
}
}
val = yearForWeekOfYear
if val != NSDateComponentUndefined {
if comps.yearForWeekOfYear != val {
return false
}
}
return true
}
return false
}
}
extension NSDateComponents : _SwiftBridgeable {
typealias SwiftType = DateComponents
var _swiftObject: SwiftType { return DateComponents(reference: self) }
}
extension DateComponents : _NSBridgeable {
typealias NSType = NSDateComponents
var _nsObject: NSType { return _bridgeToObjectiveC() }
}
extension NSCalendar: _SwiftBridgeable, _CFBridgeable {
typealias SwiftType = Calendar
var _swiftObject: SwiftType { return Calendar(reference: self) }
}
extension Calendar: _NSBridgeable, _CFBridgeable {
typealias NSType = NSCalendar
typealias CFType = CFCalendar
var _nsObject: NSCalendar { return _bridgeToObjectiveC() }
var _cfObject: CFCalendar { return _nsObject._cfObject }
}
extension CFCalendar : _NSBridgeable, _SwiftBridgeable {
typealias NSType = NSCalendar
internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) }
internal var _swiftObject: Calendar { return _nsObject._swiftObject }
}
extension NSCalendar : _StructTypeBridgeable {
public typealias _StructType = Calendar
public func _bridgeToSwift() -> Calendar {
return Calendar._unconditionallyBridgeFromObjectiveC(self)
}
}
extension NSDateComponents : _StructTypeBridgeable {
public typealias _StructType = DateComponents
public func _bridgeToSwift() -> DateComponents {
return DateComponents._unconditionallyBridgeFromObjectiveC(self)
}
}
| apache-2.0 | 3dd9a4cd89c821e355a6725bd2b9cc85 | 43.482571 | 880 | 0.629717 | 5.040425 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.